How to substring a number out of a string field using Python field calculator in ArcGIS? [duplicate]
Using ArcGIS Desktop 10.7
I want to substring numbers as text out of a string field into a new string field with field calculator so that I can use them for layer symbology. The field contains highway names such as 'I- 280' and 'State Rte 25' and I want only the '280' and '25' for a new field. Is there a Python conditional statement I can use that will substring the number regardless of digit length, placement (end or between text, eg, "State Rte 25 Bus")?
2 Answers 2
You can use a regular expression to extract numerical values from a text.
In the field calculator, select the Python parser, and check Show Codeblock.
The regular expression package should be loaded first, so set the pre-logic script to:
import re
and the script itself is:
re.search("\d+", !FULLNAME!).group(0)
\d
means: match a digit (0–9)+
means: match one or more of the previousgroup(0)
returns the first match
There's no error handling, so this may fail if FULLNAME is empty, or does not contain a digit at all.
For more information see the documentation about regular expressions in Python
-
Wow, this completely worked! Thanks!kent– kent2020年11月11日 04:06:29 +00:00Commented Nov 11, 2020 at 4:06
-
@kent Feel free to mark this as answer ;-)Berend– Berend2020年11月11日 07:53:21 +00:00Commented Nov 11, 2020 at 7:53
-
You probably need to think about edge cases where there are two or more numbers seperated by text. Just make visual spot checks of your results where the
FULLNAME
looks funny or non-standard, to see whether this really is a problem in your dataset.til_b– til_b2020年11月11日 09:25:04 +00:00Commented Nov 11, 2020 at 9:25
You could use the isdigit()
string method.
''.join((s for s in !FULLNAME! if s.isdigit()))
-
I wasn't able to get this string method to work. I tried import isdigit() as the pre-logic script code and copy/pasted the join expression as script for new field and an error is returned.kent– kent2020年11月11日 04:11:57 +00:00Commented Nov 11, 2020 at 4:11
-
You don't need to import anything.
.isdigit()
is a method of any string. What was the error? What is your dataset format (shapefile, FGDB feature class)?user2856– user28562020年11月11日 04:21:04 +00:00Commented Nov 11, 2020 at 4:21 -
Okay I got it to work. Thanks!kent– kent2020年11月12日 03:06:14 +00:00Commented Nov 12, 2020 at 3:06
Explore related questions
See similar questions with these tags.