4

I need to replace multiple words with one word in a field at one time in one script.

Example in my LettersField I need to replace all the "Aa" and all the "Bb" and all the "Cc" with "Rr".

I am aware of the replace fxn and I cannot use the find and replace tool - which would be MUCH easier but I have to create a python script.

How can I do this - what would the code block be and the 'LettersField =' be?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jul 14, 2015 at 1:47
5
  • Just for clarification, are you replacing all instances of the exact strings "Aa", "Bb" and "Cc" with the string "Rr"? Commented Jul 14, 2015 at 1:52
  • 3
    You mean str(!field!).replace('Aa', 'Rr').replace('Bb', 'Rr').replace('Cc', 'Rr')? Commented Jul 14, 2015 at 1:57
  • You can stack them !field!.replace("Aa","Rr").replace("Bb","Rr") just be careful when you do that you're not introducing a race; I'm not sure whether the replace is done left to right or right to left. @MikeT you beat me to it by seconds! Commented Jul 14, 2015 at 1:58
  • 1
    In the field calculator you should have the option to select either VB or python parser. If you select the python parser, under the string type list of functions you should find .replace(). You can use the above examples in the comments to get it to work. Commented Jul 14, 2015 at 2:00
  • Mike T - your answer worked perfectly, thank you. I was not aware you could use .replace consecutively. Commented Jul 15, 2015 at 14:31

1 Answer 1

5

If you plan to do this often you might be better off doing this as a function so you can reuse it.

  1. Open the Field Calculator
  2. Click on the Show Codeblock check box
  3. Enter the code block included below
  4. You can click on the Save button to save the code and load it later on with the Load button

Here is a screen capture as an example. enter image description here

It's the same result in the end but it may be a bit more flexible.

Pre-Logic Script Code

def rep_field(in_fld, rep_value):
 targets = ['Aa','Bb','Cc','Dd']
 for targ in targets:
 in_fld = in_fld.replace(targ, rep_value)
 return in_fld
answered Jul 14, 2015 at 9:50

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.