Hallo,
I have a field with city names and I want to slice the name in the label expression to only the 1st character.
I want to do this in python. looking at the internet i have this but it is not working:
def Label ( [CityName] 😞
s = [CityName]
s1 = s[1:]
return s1
i am working with arcgis for desktop 10.3.1
greetings Peter
Solved! Go to Solution.
That's weird, because I tested the expression on a layer with Null values in the attribute filed and it worked. How about adding a None type check in there?
def FindLabel ( [CityName] ):
try:
if [CityName] is not None:
return [CityName][:1]
except AttributeError:
pass
I got this to work:
def wtf (instring):
s= instring[:1] ####### Notice the position of the colon(:)
return s
Above is in the feild calculator, in a label expression be sure to choose python as the parser and check Advanced:
i stil got a string error
It's probably due to an empty/Null attribute value, which could be returned as None. Try this definition expression:
def FindLabel ( [CITY_CODE] ):
try:
return [CITY_CODE][:1]
except AttributeError:
pass
You could simplify the definition function even further:
def FindLabel ( [CITY_CODE] ):
return [CITY_CODE][:1]
Your right there a NULL values and that was causing the error. My code works if I remove the NULL values but I need same on NULL.
your code is giving me the same error.
Greetings Peter
That's weird, because I tested the expression on a layer with Null values in the attribute filed and it worked. How about adding a None type check in there?
def FindLabel ( [CityName] ):
try:
if [CityName] is not None:
return [CityName][:1]
except AttributeError:
pass
That is weird. i now got a other error
this is my field properstie
You have a left bracket in front of the CityName field in the if statement - I see I made the same error in my previous reply
I think it was my mistake I got a extra ( in the code.
your code is working correctly. It is a more difficult code then I would think for such a simple task but I am really glad it works.
Thank you
def FindLabel ( [CityName] ):
try:
if [CityName] is not None:
return [CityName][:1]
except AttributeError:
pass