Search code examples
pythonsplitcharactergisarcpy

ArcPy, Python- Splitting a string on multiple occurrences of a hyphen


I've got a text field in an attribute table that looks like this:

NAME_ID

Smith-123-456

Stewart-13-0931-2312

Brown-47

Jack-678-987-3-A

I've created a new text field where I want to calculate the above strings and remove the first "-" and everything to the left. My new field should look like this:

123-456

13-0931-2312

47

678-987-3-A

I tried this...

NEW_FIELD = !NAME_ID!.split("-")[1]

I thought the below code would calculate everything to the right of the first "-", but I'm only getting the string right after the first hyphen.

My results are:

123

13

47

678

How do I either strip the all characters before and including the first "-" or calculate all fields after the first "-"

Thanks in advance!


Solution

  • The split function takes a second argument, that is the number of splits to perform. Pass in a value of 1, then you'll get a list back where [0] is the first item and [1] is everything else to the right.

    >>> 'Stewart-13-0931-2312'.split('-',1)
    ['Stewart', '13-0931-2312']
    
    >>> 'Jack-678-987-3-A'.split('-',1)
    ['Jack', '678-987-3-A']