I am trying to accomplish this task: https://stackoverflow.com/questions/15851568/how-to-get-the-last-part-of-a-string-before-a-certain-character within the Field Calculator.

I have the below but cannot get it to run.

What am I missing?

enter image description here

1 Answer 1


You are using the syntax from the question, not the answer. Also, the pre-logic code for Python can't reference field names. You also might want to check out .rpartition().

You shouldn't have to use pre-logic at all:

Sector = !FolderPath!.rsplit("/")[0]

But if you did want to use pre-logic, here's how to do it:

def sect(field):
   return field.rsplit("/")[0]

Sector = sect(!FolderPath!)

With that being said, if you are splitting pathnames, I encourage you to check out os.path.split() instead (Python docs). It's a lot simpler to deal with pathnames this way and is the more pythonic route.

Edit for slicing:

a = [1, "fish", 2, "fish", "red fish", "blue fish"]
a[0] -> 1
a[1] -> "fish"
a[2] -> 2
a[-1] -> "blue fish"
a[0:2] -> [1, "fish"]
  • thanks for clarifying my overcomplication. Your suggestions works, but I need it to run from the end of the string. I added a colon before the 0 but that does not work.
    – mikeLdub
    Jul 28, 2014 at 16:24
  • @mikeLdub Ahh, I've updated my code to reflect that.
    – Paul
    Jul 28, 2014 at 16:25
  • 1
    Or os.path.dirname()/os.path.basename() if you're only interested in the head/tail of the path, rather than both parts in a tuple.
    – nmpeterson
    Jul 28, 2014 at 16:25
  • @nmpeterson, yes good point! Definitely the better option if you only need one, which OP probably does. I assume he wants the head, but I'm not sure.
    – Paul
    Jul 28, 2014 at 16:28
  • 1
    @mikeLdub, you need to look up slicing syntax. The number inside the brackets refers to which number in the list to return. I've edited my post to give a brief overview of slicing. So, you'll probably want to change [0] to [1]
    – Paul
    Jul 28, 2014 at 16:34

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.