Reputation: 151
def parse_distance(string):
# write the pattern
pp = re.compile("\d+")
result = pp.search(string)
if True:
# turn the result to an integer and return it
dist = int(result)
return dist
else:
return None
parse_distance("LaMarcus Aldridge misses 13-foot two point shot")
I need to get 13 from the string showed above and it gives me error that int(result) has error of being not string. So I need to get the number from string and turn it to integer, how can I do it thanks.
Upvotes: 0
Views: 60
Reputation: 473853
You need to get the matched digits from the group()
:
def parse_distance(string):
pp = re.compile(r"(\d+)-foot")
match = pp.search(string)
return int(match.group(1)) if match else None
Some sample usages:
>>> print(parse_distance("LaMarcus Aldridge misses 13-foot two point shot"))
13
>>> print(parse_distance("LaMarcus Aldridge misses 1300-foot two point shot"))
1300
>>> print(parse_distance("No digits"))
None
Upvotes: 3
Reputation: 255
Seems you want to extract digit from given string;
import re
In [14]: sentence = "LaMarcus Aldridge misses 13-foot two point shot"
In [15]: result = re.findall('\d+', sentence)
In [16]: print result
['13']
In [17]: [int(number) for number in result ]
Out[17]: [13]
or;
In [19]: result = [int(r) for r in re.findall('\d+', sentence)]
In [20]: result
Out[20]: [13]
Upvotes: 0