Is there a way to strip characters from a string using python? The string is varied in length...

Examples of strings: Interstate 10 Auxiliary road 24 State highway 14

I am looking for just the numbers. 10 24 14

I am attempting to automate labeling roads by populating symbols with the numbers stripped from the strings.

The info I am working with is in an attribute table I am using ArcMap 10.2.

I am new to python and very interested to learn if this sort of functionality is available.


The link offered by Kevin does the job but it won't clean the extra spaces. Use this python expression:

import re
inputText = "12 Interstate 10 Auxiliary road 24 Sta1te highway 14"
t = re.sub("[^0-9 ]", "", inputText)
resultText = ' '.join(t.split())

it outputs: '12 10 24 1 14'

To use this simple script with ArcGIS lable expression, see the snapshot:

label expression remove non-numeric characters

  • Can you import modules in a label expression? – Erica Feb 12 '15 at 17:40
  • 2
    Yes you can, importing textwrap in label expressions works. – crmackey Feb 12 '15 at 17:49
  • 1
    Thanks so much for the prompt responses. My map roads labeled like a dream. I can't wait to share this with my class mates and teacher. – Robin Feb 12 '15 at 18:23

Instead of using a RegX, another option you could use would just be a single line using the string join and isdigit() test.

"".join(c for c in [NAME] if c.isdigit())

I just tried that for my roads layer (make sure the parser is set to Python) in ArcGIS Desktop 10.1 and it pulled out the road numbers very nicely. Only thing to note, non-numeric roads will go unlabeled that way, so, you may have to set up label classes to label numeric roads and named roads differently.

Obviously in the code above, replace [NAME] with your appropriate field name.

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.