# Extracting numbers from string field using Python Parser of ArcMap Field Calculator?

I am trying to calculate field test2 with only the numeric values from a string field test. The entire script is like:

def makestr(test)
list=[]
for s in test:
if s.isdigit():
list.append(s)
for a in list:
str=''.join(list)

But I keep getting an error:

Any ideas?

• isdigit() checks whether the entire thing is a number, not whether a part of it is. So even if your strings contain numbers it would never return true, they have to be exclusively numbers. I think your best best would be to look at regular expressions. See here. Feb 9, 2015 at 12:33
• With the for loop (for s in test) I check every character separately whether is numeric or not. Feb 9, 2015 at 12:44
• Please always include the text, not just picture, for error messages to aid future searches by people having the same problem.
– PolyGeo
Feb 9, 2015 at 12:57
• If your input string is "abc123.456de789", you will return 123456789. Is that what you want? Furthermore, you are returning this as a string, not a number. Feb 9, 2015 at 15:36
• yes this is what i want , Feb 9, 2015 at 19:05

Try this:

numlist = []   # Don't use name "list"
for s in test:
if s.isdigit():
numlist.append(s)
return ''.join(numlist)  # Return a value

You are defining the function on the first statement, which needs to end in a ":", e.g.

def makestr(test):

Here is a simple solution:

def makestr(test):
try:
return ''.join(i for i in test if i.isdigit())
except ValueError:
pass
• Thank you for your point, I omitted that, unfortunately no success, the error message i get now is 539 Feb 9, 2015 at 13:37

I found also another error. You have to join the a values at the last loop:

def makestr(test):
l1=[]
for val in test:
if val.isdigit():
l1.append(val)
return " ".join(l1)

or

def makestr(test):
l1 =[val for val in test if val.isdigit()]
return " ".join(l1)

You can join list items without iterating over them. Just use the join fuction with the list as argument. It is better not to name variables "str" or "list" because thay are python built-in names, which can cause problems.