1

Trying to return everything except the last element in a field after splitting it. Using ArcMap 10.2.2 in the field calculator.

!ST_NAME!.split(" ")[:-1]

This returns a null value in attribute table. If a I use the same approach in python interactive window it seems to work:

a = "Johnny be good"

>>> b = a.split(" ")[0:-1]
>>> b
['Johnny', 'be']
2
  • 5
    The return value is a list, which is not compatible to the field, which is rejected by the parser hence the null value. To use this in a field calculation for a string field you need to 'join' it " ".join(!ST_NAME!.split(" ")[:-1]) to make it into a string. Commented Apr 25, 2016 at 22:11
  • Another approach you can use would be to find the rightmost space and then slice into the string with that index. f = "101 first street"; f[:f.rfind(" ")]
    – Paul
    Commented Apr 25, 2016 at 23:22

1 Answer 1

3

Expanding on my previous comment...

The problem with your statement is that the returned value from string.split is a list and the field you're trying to calculate into is a string, these types are incompatible so the parser ignores the value and sets the string to null.

To turn a list into a string you need to use join:

>>> a = "Johnny be good"
>>> b = a.split(" ")[0:-1]
>>> print b
['Johnny', 'be']
>>> c = " ".join(b)
>>> print c
Johnny be
>>> 

b is a list object, c is a string... So to field calculate everything but the last word in a string into a string field use:

" ".join(!ST_NAME!.split(" ")[:-1]) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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