Search code examples
pythonarcgisarcmaplabeling

Collect last word from varied length string for filtering, auto labeling and column population?


I have been looking and reading for a few days about how to collect the last word from a varied length string. I have found lots of postings about how to collect/split the last word, but none of the content I have read addresses varied length stings.

I would like to use this function for column population, automated labeling and content filtering from inside either the field calculator or label expression interfaces.

String examples: Morgan County, Johnson Parrish, John Brown County, Rick de la Rosa City, Big Wild life Area.

Output example : County, Parish, City, Area

Nothing I have tried has worked 100%. The following code just about works, and would work if all my strings were two words long: s.split( " " )[1:][0]

I am using arcmap 10.2 / python


Solution

  • How about this:

    # example comma separated string ending with a period
    s = "Morgan County, Johnson Parrish, John Brown County, Rick de la Rosa City, Big Wild life Area."
    
    # output list
    out = []
    
    for pair in s.replace('.', '').split(', '):
        out.append(pair.split(' ')[-1])
    
    print out
    

    Which results in: ['County', 'Parrish', 'County', 'City', 'Area']