1

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?

  • Should "WESTON" be replaced with "W"? It is unclear what values are to be expected in that field. In any event I think this question is much more Python than ArcPy and so should be researched at Stack Overflow. – PolyGeo Aug 14 '17 at 19:15
3

You can try this:

Predir field has already North, South, East, West

 !Predir![0:1]
  • good idea to shorten the code – atxgis Aug 14 '17 at 17:10
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)
0

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
0

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!).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.