Labeling: Extract specific letters from string

350
3
02-28-2024 01:47 AM
Frida_questions
New Contributor

Hello!

I could really use some help with a function. I have no experience with phyton and this seems like it could be fairly difficult.

I am trying to label my features. I have a field [trakt] from which i would like to extract the first letter, and if there is a space, I would also want to extract the first letter after that space.

The field [trakt] has names in it, for example it could be "South Sweden", "North Sweden" and "Sweden". If the name is "North Sweden" I would like the script to return "NS", but if the name is "Sweden", the script should return only "S". But in reality I have about 50 different names I would like to do this with (edited).

 

Is this problem possible to solve?

Tags (1)
3 Replies
DanPatterson
MVP Esteemed Contributor

verbose so you can follow

python parser,

`a` is your field as an example

code block

a = ["South Sweden", "North Sweden", "Sweden"]

def sp(fld):
    if " " in fld:
        spl = fld.split(" ")
        return spl[0][0] + spl[1][0]
    else:
        return fld[0]
        

[sp(i) for i in a]
['SS', 'NS', 'S']

calculator expression

sp(!trakt!)


... sort of retired...
0 Kudos
Frida_questions
New Contributor

Oh thank you! But if I have 50 names rather than just 3, is there a way to do this generally, or do I have to specify all 50 ?

0 Kudos
DanPatterson
MVP Esteemed Contributor

It will do it for all.  This is a field calculator function


... sort of retired...