Select to view content in your preferred language

How to slice a word in the label expression

3361
10
Jump to solution
12-07-2016 12:23 PM
PeterVersteeg
Frequent Contributor

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 Emeritus

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
Frequent Contributor

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
Frequent Contributor

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
Frequent Contributor

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
Frequent Contributor

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