Select to view content in your preferred language

Remove letters and special characters from an alpha numeric string using python

32454
11
Jump to solution
11-15-2012 03:01 PM
JessicaKirby
Deactivated User
Hi All,
I need to find a way to remove all letters and special characters from a string so that all i am left with is numbers using python.
The end goal is to use this code in the python code block in the Calculate Field GP tool.

I have a field called Lease_Num
It contains a string such as ML-26588 , ML 25899, UTLM58778A
So sometimes it has a dash, sometimes it has a space and sometime it has nothing.  The Alpha characters can be any length and the numbers can be any length.  Sometime their can even be an alpha character at the end of the string...its totally random

I need to strip out the the alpha's and any special characters or spaces from the string to leave me with just the number.

Can someone help me with how I would do this and then tell me how to apply it to the code block on Calculate Field GP tool.

Many thanks!
Tags (2)
11 Replies
curtvprice
MVP Alum
Now, I just want to remove the Alpha Characters only(which can be at any place) and nothing else.


One extremely nice thing about Python is you can easily experiment at an interactive command line and tweak your code to get what you want, for example:

>>> ''.join([i for i in "62/A" if i.isdigit()])
'62'
>>> ''.join([i for i in "62/A" if not i.isalpha()])
'62/'


Can anyone help me with the code (Python or SQL).

SQL is almost always used in ArcGIS to select records - not to calculate fields.
0 Kudos
FilipKrál
Frequent Contributor
Hi,
Powerful and flexible function for these kinds of manipulations is the 'sub' function from the 're' (regular expressions) module.
The module is normally installed by default.
import re
re.sub(r'\W', '', "A/62")


See other uses here:
http://docs.python.org/2/howto/regex.html#matching-characters