How to slice a word in the label expression

1713
10
Jump to solution
12-07-2016 12:23 PM
PeterVersteeg
Occasional Contributor II

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

0 Kudos
1 Solution

Accepted Solutions
FC_Basson
MVP Regular Contributor

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‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

View solution in original post

10 Replies
JoeBorgione
MVP Esteemed Contributor

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:

That should just about do it....
PeterVersteeg
Occasional Contributor II

i stil got a string error

0 Kudos
FC_Basson
MVP Regular Contributor

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‍‍‍‍‍‍‍‍‍‍
FC_Basson
MVP Regular Contributor

You could simplify the definition function even further:

def FindLabel ( [CITY_CODE] ):
   return [CITY_CODE][:1]
PeterVersteeg
Occasional Contributor II

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

0 Kudos
FC_Basson
MVP Regular Contributor

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‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
PeterVersteeg
Occasional Contributor II

That is weird. i now got a other error

this is my field properstie

0 Kudos
FC_Basson
MVP Regular Contributor

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 

0 Kudos
PeterVersteeg
Occasional Contributor II

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
0 Kudos