I have field in an attribute table populated with expressions like "6S2Olch1E", "10S1B", "9B3S2Olch" and so on. I need to make a numeric filed populated with only numbers associeted with letter S from those experessions (f.e. 6 if expression is "6S2Olch1E" or 10 if it's "10S1B"). Is there a way to do this using a script in Field Calculator? I'm not a programmer.
-
Could you please give more examples of the intended output? For example, how do you want to handle cases such as "42S6S2OIch1E" or "E42ms42S6S2OIch1E" or "43hj56g7887SlkjhLKJH1234"?– Aaron ♦Commented Oct 3, 2015 at 21:28
-
Fortunately, I don't have such cases. My expressions are forest stand formulas: each letter or group of letters stands for some woody species and each number stands for a coefficient of a species abundance.– ZoyaCommented Oct 3, 2015 at 22:00
Add a comment
|
1 Answer
Standalone code
def f(s):
idx = s.upper().index('S')
s = s[:idx]
for i in reversed(range(len(s))):
if s[i].isalpha():
s = s[i+1:]
break
if s.isdigit():
return int(s)
else:
return 0
Testing
print f("S2Olch1E")
#0
print f("6S2Olch1E")
#6
print f("5B66S2Olch1E")
#66
print f("54F5456B666S2Olch1E")
#666
In your expression (Field Calculator), just use:
f(!fieldName!)
-
I put a name of my field in the "f(!fieldName!)" expression but when I try to run the script a massage is shown "A field name was not found or there were unbalanced quotation marks". What I'm doing wrong?– ZoyaCommented Oct 3, 2015 at 21:04
-
@Zoya, have you chosen python in field calculator? (remove both " from the string). gis.stackexchange.com/questions/67593/help-in-field-calculator Commented Oct 3, 2015 at 21:37
-
I have Arcgis 9 and in its Field Calculator that opens from an attribute table there is no Python option. But I've just used Field Calculator from Data Management Tools, chose Python and it worked like a charm. Thanks a lot Farid Cher!!!– ZoyaCommented Oct 3, 2015 at 21:57
-