我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?

例子:

line = "hello 12 hi 89"

结果:

[12, 89]

当前回答

此答案还包含数字在字符串中为浮点数的情况

def get_first_nbr_from_str(input_str):
    '''
    :param input_str: strings that contains digit and words
    :return: the number extracted from the input_str
    demo:
    'ab324.23.123xyz': 324.23
    '.5abc44': 0.5
    '''
    if not input_str and not isinstance(input_str, str):
        return 0
    out_number = ''
    for ele in input_str:
        if (ele == '.' and '.' not in out_number) or ele.isdigit():
            out_number += ele
        elif out_number:
            break
    return float(out_number)

其他回答

使用下面的正则表达式是一种方法

lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
        match = re.search(repl_str, word)
        if match:
            output.append(float(match.group()))
print (output)

和findall Re.findall (r'\d+', "hello 12 hi 89")

['12', '89']

re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")

['12', '89', '777']

我很惊讶地发现还没有人提到itertools的用法。Groupby作为实现这一目标的替代方案。

你可以使用itertools.groupby()和str.isdigit()来从字符串中提取数字,如下:

from itertools import groupby
my_str = "hello 12 hi 89"

l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]

由l保持的值将是:

[12, 89]

PS:这只是为了说明,作为一种替代方案,我们也可以使用groupby来实现这一点。但这不是一个推荐的解决方案。如果您想实现这一点,您应该使用基于使用str.isdigit作为过滤器的列表理解的fmark的接受答案。

如果你知道字符串中只有一个数字,比如'hello 12 hi',你可以尝试filter。

例如:

In [1]: int(''.join(filter(str.isdigit, '200 grams')))
Out[1]: 200
In [2]: int(''.join(filter(str.isdigit, 'Counters: 55')))
Out[2]: 55
In [3]: int(''.join(filter(str.isdigit, 'more than 23 times')))
Out[3]: 23

但是要小心!!:

In [4]: int(''.join(filter(str.isdigit, '200 grams 5')))
Out[4]: 2005
line2 = "hello 12 hi 89"  # this is the given string 
temp1 = re.findall(r'\d+', line2) # find number of digits through regular expression
res2 = list(map(int, temp1))
print(res2)

可以使用findall表达式通过digit搜索字符串中的所有整数。

在第二步中,创建一个列表res2,并将string中找到的数字添加到该列表中。

我只是添加这个答案,因为没有人添加一个使用异常处理,因为这也适用于浮动

a = []
line = "abcd 1234 efgh 56.78 ij"
for word in line.split():
    try:
        a.append(float(word))
    except ValueError:
        pass
print(a)

输出:

[1234.0, 56.78]