I want to parse a text field into a floating point field. (e.g.: "10-Inches Bituminous Concrete 8-Inches Portland Cement Concrete 6-Inches Crushed Stone Base" becomes "10")
There are of course many ways to do this kind of thing. Here's one way:
>>> text = "10 asdf 12"
>>> [c for c in text if c.isdigit() or c.isspace()]
['1', '0', ' ', ' ', '1', '2']
>>> "".join([c for c in text if c.isdigit() or c.isspace()])
'10 12'
>>>
Here's a function you can use that does this:
def GetNum(text):
text = text.strip()
text = "".join([c for c in text if c.isdigit() or c.isspace()])
try:
num = float(text.split()[0])
except:
num = None
return num
Here's an enhanced version that works if there are no spaces between the numbers:
def GetNum(text):
text = text.strip()
c1 = list()
for c in text:
if c.isdigit():
c1 += c
else:
c1 += " "
try:
num = float("".join(c1).split()[0])
except:
num = None
return num