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?

  • Just for clarification, are you replacing all instances of the exact strings "Aa", "Bb" and "Cc" with the string "Rr"? – Fezter Jul 14 '15 at 1:52
  • 3
    You mean str(!field!).replace('Aa', 'Rr').replace('Bb', 'Rr').replace('Cc', 'Rr')? – Mike T Jul 14 '15 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! – Michael Stimson Jul 14 '15 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. – TsvGis Jul 14 '15 at 2:00
  • Mike T - your answer worked perfectly, thank you. I was not aware you could use .replace consecutively. – user55183 Jul 15 '15 at 14:31
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

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.