Is it possible to remove more than 1 character from a string in a field using the field calculator?
I know
!file!.replace(" ","")
removes spaces in a string, but is it possible to remove spaces and other characters such as "!", "?", "," all at once?
I have also tried:
Pre Logic Script:
def replChars(Name):
replaceChars = ["!","?",","]
for char in replaceChars:
Name.replace(char,"")
Field =
replChars(!NH_NAME!)
3 Answers 3
Even though this question can be considered off topic I though I would make a suggestion.
Try using the Python re module in the Field Calculator. Here is a simple example used in the ArcMap field calculator.
Pre-Logic Script Code
import re
def repChar(strg)
regexChars = '[!@$*#]'
line = re.sub(regexChars,'',x)
return line
Field
repChar(strg)
I know this isn't a very detailed excample but it's all I have time for at the moment.
-
Does the field calculator recognize imported modules?coffee and gis– coffee and gis2016年05月16日 22:04:37 +00:00Commented May 16, 2016 at 22:04
-
3Yes it does. I've done this many times with no problem.. you don't want to get too complex as there's no debugging though.Michael Stimson– Michael Stimson2016年05月16日 22:05:18 +00:00Commented May 16, 2016 at 22:05
Your single line
!file!.replace(" ","")
can be added to by including more .replace()
!file!.replace(" ","").replace("?","").replace(",","").replace(chr(33),"")
and so on. You may need to escape some of the characters, or use their chr()
code if the field calculator doesn't like them. chr(33)
in my example replaces the !
.
Chr codes can be retrieved from: http://www.ascii-code.com/ or by opening the python window in ArcMap and typing ord("!")
, for example, or whatever character you want to find into ord()
.
-
Thank you for this. Where can I get a list of chr codes?coffee and gis– coffee and gis2016年05月16日 22:25:21 +00:00Commented May 16, 2016 at 22:25
-
3They're ASCII codes, try ascii-code.comMichael Stimson– Michael Stimson2016年05月16日 22:26:13 +00:00Commented May 16, 2016 at 22:26
-
1or in the python window type
ord("!")
which will return thechr()
code33
. Put whatever character you want to find intoord()
2016年05月16日 22:27:56 +00:00Commented May 16, 2016 at 22:27 -
This worked wonderfully! I love the simplicity of it! I did not know adding more
.replace()
after the first one was possible. Thank you so very much!coffee and gis– coffee and gis2016年05月16日 22:34:09 +00:00Commented May 16, 2016 at 22:34 -
Could the down-voter please leave a comment?2016年05月16日 22:44:52 +00:00Commented May 16, 2016 at 22:44
It's not pretty, but
''.join([x for x in list(!file!) if x not in ["!","@","$"]])
should remove any single character you specify in the list, and return the resulting characters as a string (the "etc" in your example wouldn't work, however).
Explore related questions
See similar questions with these tags.
!
may cause problems and may need to be escaped due to arcpy using!
to identify field names