Select to view content in your preferred language

Split field on first number

3870
11
Jump to solution
01-14-2016 02:32 PM
DanielAmrine
Frequent Contributor

Edit (by Xander Bakker): the original question was placed at this thread: Extracting an integer from a string field but I decided to branch it to a new thread.

I have a similar situation...

For Example:

s ="POWERS 1C-23HZ"

and some are like s2 = RATTLER4C-34HZ

I would like to tell python to find the first number in each field and then split the field at the same location at the first number. so....

Field 1 = RATTLER

Field 2 = 4C-34HZ

derived from the string above: s2

I would like to use the field calculator to do this.

I know you can use this to split on the space:

!field! = s.split(' ')[0]

I did this in the field calculator expression box and it works but only on the strings with a space where I need to break it.

Any help is much appreciated!

Dan A.

Message was edited by: Xander Bakker. Post branched to new Thread

0 Kudos
11 Replies
BlakeTerhune
MVP Regular Contributor

How about something like this?

s ="POWERS 1C-23HZ"
s2 = "RATTLER4C-34HZ"
for string in (s, s2):
    string = string.replace(" ", "")  ## Drop spaces (optional)
    print string
    string_builder = ""
    field_vals = None
    for i in string:
        if i.isdigit():
            field_vals = (
                string[:len(string_builder)],  ## string before number
                string[len(string_builder):]  ## string after number
            )
            print field_vals
            break
        else:
            string_builder += i

I am not clear on how you want to use field calculator to write to two output fields, so I'll let you clarify your intent or adapt this logic to your specific need. You'll at least need to get rid of the first three lines.

EDIT:​ Xander and Darren beat me to it!

DanielAmrine
Frequent Contributor

I apologize

I should of started a new post but i don't think people would have seen or replied to it as quickly if i had done that!

Thank you all for the ideas. I realize now i will have to do one field at a time if i use the calculator.

Thank you Xander for laying it out like you did....it was very helpful.

Dan

0 Kudos