如何从给定字符串中提取数字

时间:2016-02-04 21:48:37

标签: python regex python-3.x

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")

我需要从上面显示的字符串中得到13并且它给出了错误,即int(结果)有错误的不是字符串。所以我需要从字符串中获取数字并将其转换为整数,我该怎么做呢谢谢。

2 个答案:

答案 0 :(得分:3)

您需要获取group()

中匹配的数字
def parse_distance(string):
    pp = re.compile(r"(\d+)-foot")
    match = pp.search(string)
    return int(match.group(1)) if match else None

一些示例用法:

>>> 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

答案 1 :(得分:0)

似乎你想从给定的字符串中提取数字;

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]

In [19]: result = [int(r) for r in  re.findall('\d+', sentence)]
In [20]: result
Out[20]: [13]