I work in ArcMap 10.8.1. I have a field which contains values in format of "x 1", "x 2", "x 1" etc. A number + one to five empty spaces and a "1" or "2". I want to replace them using the Field Calculator. So the replaced value is "x 1" -> "x_1"; "x 2" -> "x_2" and so on.

I Calculate new values with this code in Python parser: !FieldName!.replace(" 2","_2") and this doesn't work. It just replaces "2" with "_2". I need to get rid of empty spaces too. I also tried !FieldName!.replace("" "2","_2") which returns an error.

Is there a way to type in empty values into the code?

  • Are you saying you could have "x.1" or "x.....1" where a dot is representing a single space character? In both cases you want it to become "x_1"?
    – Hornbydd
    Dec 6, 2021 at 15:08
  • Exactly that, yes.
    – M. Tomas
    Dec 6, 2021 at 15:15

1 Answer 1


You need to use a regular expression to capture that one or more spaces to be replaced with a single underscore.

Run a field calculate as shown below on the field, in my example I have a text field called test

Field Calculate

The code is:

import re
def replacespace(s):
  return re.sub(" +","_",s)

Note it is a single space before the + symbol


Your Answer

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

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