I'm attempting to modify my feature labels such that the "NB", "SB", "WB", and "EB" portion of the string is removed:
E.g. "CEDAR AVE NB" --> "CEDAR AVE" or "ROBERT TRL S SB" --> "ROBERT TRL S"
The code I have so far is as follows (I am new to coding):
def FindLabel([StreetName]):
L = [StreetName]
L1 = L.split(" ")
if len(L1)["NB", "SB", "WB, "EB"] in L1
return L1[0] + " " + L1[1]
L1 = L
FindLabel = L
Would anyone be able to provide help? In the script, I'm looking to utilize the split method, len function and in keyword in order to break up the string into word parts, return the number of items in the string and check if the values "NB", "SB", "WB", or "EB" are present in the string, respectively.
2 Answers 2
This approach checks the last 'word' in your string to see if it matches one of the strings you want to eliminate:
def FindLabel ([StreetName]):
input_string = [StreetName]
split_string = input_string.split()
if split_string[-1] in ["NB", "SB", "EB", "WB"]:
return " ".join(split_string[:-1])
else:
return input_string
I don't know much about Arcmap syntax for label expressions, but using Python, you could do something like:
def FindLabel ([StreetName]):
import re
input_string = [StreetName]
# Regular expression that look for strings ending with a space character
# followed by either NB, SB, EB or WB, and replace this part by an empty string
return re.sub("\s*[NSEW]B$", "", input_string)
That is, assuming you can import modules like re
Otherwise, you can use the following snippet
def FindLabel ([StreetName]):
input_string = [StreetName]
for ending in (" NB", " SB", " EB", " WB"):
if input_string.endswith(ending):
return input_string[:-len(ending)]
return input_string
Explore related questions
See similar questions with these tags.