enter image description here
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:
enter image description here
Any ideas?
-
1isdigit() 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.BritishSteel– BritishSteel2015年02月09日 12:33:03 +00:00Commented Feb 9, 2015 at 12:33
-
With the for loop (for s in test) I check every character separately whether is numeric or not.Stelios Tselepis– Stelios Tselepis2015年02月09日 12:44:31 +00:00Commented Feb 9, 2015 at 12:44
-
1Please always include the text, not just picture, for error messages to aid future searches by people having the same problem.PolyGeo– PolyGeo ♦2015年02月09日 12:57:18 +00:00Commented 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.Llaves– Llaves2015年02月09日 15:36:41 +00:00Commented Feb 9, 2015 at 15:36
-
yes this is what i want ,Stelios Tselepis– Stelios Tselepis2015年02月09日 19:05:45 +00:00Commented Feb 9, 2015 at 19:05
3 Answers 3
Try this:
def makestr(test): # Add colon
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 539Stelios Tselepis– Stelios Tselepis2015年02月09日 13:37:27 +00:00Commented 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.
Explore related questions
See similar questions with these tags.