Select to view content in your preferred language

VB or Python script for County label that drops the last word in a field

7209
14
Jump to solution
05-19-2014 02:14 PM
TiaMorita
Deactivated User
I am trying to create labels for a county field name (called "Name") where I drop the last word "county". For example, the Name field has "Los Angeles County" and "Santa Barbara County" and "Ventura County" - but I just want these labels in my map to read: Los Angeles, Santa Barbara, and Ventura. Is there a way to delete the last characters or just drop the whole word County in a script?

Thanks!
Tags (2)
0 Kudos
14 Replies
JoshuaChisholm
Frequent Contributor
Hello Tia,

My apologies, .rstrip() isn't exactly what I thought it was. You should probably use Greg's .replace() method.

Good luck!
0 Kudos
TiaMorita
Deactivated User
Ok. This works on your sample data.

In Field Calculator...

1. Change parser to python
2. Check Show codeblock
3. Paste the code below into Pre-logic script code
4. in the name = box, enter losemunitype(!name!)

def losemunitype( name):
    lsttypes = ['County', 'Parish', 'Borough', 'Municipality', 'Census Area', 'City and Borough']
    for losetype in lsttypes:
        if losetype in name:
            return name.replace(losetype, '')
    return name 



AWESOME! Works like a dream! Thanks!!
0 Kudos
RaymondHuang
Regular Contributor
Hi Tia,

Great!! I think you should help to mark the post by Greg as the answer. 🙂

Raymond
0 Kudos
Zeke
by
Honored Contributor
One caveat to the script: it does what you asked, but if you had any of the words in the list that precede the part you want to retain, it will delete those as well. So 'County of Los Angeles' becomes ' of Los Angeles'. If you want 'County of ' deleted, add that to the list. If you only want 'County' deleted when it's at the end, change this line:

if losetype in name:

to

if name.endswith(losetype):


0 Kudos
JoshuaChisholm
Frequent Contributor
If you only want to remove the suffix strings from the end of the name field, you could modify Greg's script like this:

def losemunitype( name):
    lsttypes = ['County', 'Parish', 'Borough', 'Municipality', 'Census Area', 'City and Borough']
    for losetype in lsttypes:
        if name.endswith(losetype):
            return name[:-len(losetype)].strip()
    return name

[INDENT]The .strip() just gets rid of the space left over at the new end of the string.[/INDENT]


PS. I switch the green check to Greg's original response. I hope that's ok!
0 Kudos