I'm using the Field Calculator .replace function to replace WEST, EAST, NORTH, SOUTH to W, E, N and S and I'm using 4 scripts !PREDIR!.replace("WEST*","W")
and so forth.
I would like to use one string to do this, how can I do this?
I'm using the Field Calculator .replace function to replace WEST, EAST, NORTH, SOUTH to W, E, N and S and I'm using 4 scripts !PREDIR!.replace("WEST*","W")
and so forth.
I would like to use one string to do this, how can I do this?
You can try this:
Predir field has already North, South, East, West
!Predir![0:1]
Python allows you to string together functions. In your case, you can string together multiple .replace()
functions into a single line of code in the field calculator.
!PREDIR!.replace('NORTH', 'N').replace('SOUTH', 'S').replace('EAST', 'E').replace('WEST', 'W').replace('west', 'W)
Use a dictionary:
ReplaceDict = { "WEST": "W",
"EAST": "E",
"NORTH": "N",
"SOUTH": "S"}
for r in ReplaceDict:
if !PREDIR! in r:
!PREDIR!.replace(r,ReplaceDict[r])
else:
pass
The closest thing to "one string" would be to use a regex:
import re
predir = re.sub(r'([NSEW])[OAE][UR]?[ST][TH]\*', r'\1', !PREDIR!)
The question then becomes if it's better to have four readable lines, or one unreadable one that may have some gotchas (the above will shorten WORST* to W too!).