简体   繁体   中英

How can I extract digits from given string

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM