0

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")?

enter image description here

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Nov 10, 2020 at 7:59
0

2 Answers 2

1

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 previous
  • group(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

answered Nov 10, 2020 at 8:16
3
  • Wow, this completely worked! Thanks! Commented Nov 11, 2020 at 4:06
  • @kent Feel free to mark this as answer ;-) Commented 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. Commented Nov 11, 2020 at 9:25
0

You could use the isdigit() string method.

''.join((s for s in !FULLNAME! if s.isdigit()))
answered Nov 10, 2020 at 8:05
3
  • 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. Commented 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)? Commented Nov 11, 2020 at 4:21
  • Okay I got it to work. Thanks! Commented Nov 12, 2020 at 3:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.