Geographic Information Systems Asked by Stelios Tselepis on February 12, 2021
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?
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
Answered by artwork21 on February 12, 2021
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.
Answered by Martin on February 12, 2021
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
Answered by nmpeterson on February 12, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP