Select to view content in your preferred language

Field calculator to extract string

181
3
Jump to solution
3 weeks ago
ALBJORGUI
Regular Contributor

Hi all, I am trying to get field calculator to help me extract a string from a field and calculate in another field.

NameInfo
ABCDEFG_(0.2014HA)!Place!.split('(')[1].split(')')[0] 
ABCDEFG (TESTXX) (123HA)??

 

So for the first field the calculation will get me the value in brackets so I end up with 0.2014HA which is great.

How would I do it for the second one? I want to extract only what is in the second bracket and ignore the first one

Thanks a lot in advance!

0 Kudos
2 Solutions

Accepted Solutions
DanPatterson
MVP Esteemed Contributor
a = 'ABCDEFG_(0.2014HA)'
b = 'ABCDEFG (TESTXX) (123HA)'

a[a.find("("):].split(" ")[-1][1:-1]
'0.2014HA'
b[b.find("("):].split(" ")[-1][1:-1]
'123HA'

# ---- yielding a code block for your 'fld'

def splitter(fld):
    """Split on a unique case"""
    val = fld[fld.find("("):].split(" ")[-1][1:-1]
    return val
    

splitter(a)
'0.2014HA'

splitter(b)
'123HA'

morning brain refresher


... sort of retired...

View solution in original post

ALBJORGUI
Regular Contributor

I found another way of doing it too.

!Name!.split('(')[2].split(')')[0]

View solution in original post

0 Kudos
3 Replies
DanPatterson
MVP Esteemed Contributor
a = 'ABCDEFG_(0.2014HA)'
b = 'ABCDEFG (TESTXX) (123HA)'

a[a.find("("):].split(" ")[-1][1:-1]
'0.2014HA'
b[b.find("("):].split(" ")[-1][1:-1]
'123HA'

# ---- yielding a code block for your 'fld'

def splitter(fld):
    """Split on a unique case"""
    val = fld[fld.find("("):].split(" ")[-1][1:-1]
    return val
    

splitter(a)
'0.2014HA'

splitter(b)
'123HA'

morning brain refresher


... sort of retired...
ALBJORGUI
Regular Contributor

I found another way of doing it too.

!Name!.split('(')[2].split(')')[0]

0 Kudos
DanPatterson
MVP Esteemed Contributor

True, but yours fails for the first case

a.split('(')[2].split(')')[0]
Traceback (most recent call last):

  Cell In[3], line 1
    a.split('(')[2].split(')')[0]

IndexError: list index out of range


b.split('(')[2].split(')')[0]
 '123HA'

where as the function in my example works for both


... sort of retired...
0 Kudos