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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Aug 14, 2017 at 15:52
1
  • 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. Commented Aug 14, 2017 at 19:15

4 Answers 4

3

You can try this:

Predir field has already North, South, East, West

 !Predir![0:1]
answered Aug 14, 2017 at 16:44
1
  • good idea to shorten the code Commented Aug 14, 2017 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)
answered Aug 14, 2017 at 17:30
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
answered Aug 14, 2017 at 16:07
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!).

answered Aug 14, 2017 at 16:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.