1

I am new on Python and using Python within ArcGIS and a bit stuck hoping someone could point me in the right direction.

I want to remove the 6 last characters if the field is longer than 6 characters. I'm using the script in the field calculator.

def doThis(fld):
    val = 0
    if len(fld) > 6:
        val = fld[len(fld)-6]
    return val
    else:
        val = fld
    return val


Dothis( !Asset_ref!)

With the code above I get a SyntaxError: Invalid syntax (line6)

  • 4
    You haven't used Python string slicing syntax, and you have too many return directives (or wrong indent). Hint: "line 6" sometimes means "on line 5, making parse on line 6 invalid" – Vince Apr 26 '17 at 10:53
4

This is the code you would need to use in the code block:

Pre-logic script:

def truncate_string(value):
  if len(value) > 6:
    return value[0:-6]
  else:
    return value

Call:

truncate_string( !CITY_NAME! )

Result:

CITY_NAME   ShortName
ABCDEFGHIJKL ABCDEF
Abilene A
Abington    Ab
Ada Ada
Addison A
Adelphi A
Adrian  Adrian
Affton  Affton
Agoura Hills    Agoura
Akron   Akron
Alameda A
Alamo   Alamo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.