我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
我找到的最佳选择如下。它将提取一个数字,并可以消除任何类型的字符。
def extract_nbr(input_str):
if input_str is None or input_str == '':
return 0
out_number = ''
for ele in input_str:
if ele.isdigit():
out_number += ele
return float(out_number)
其他回答
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中找到的数字添加到该列表中。
我假设你想要浮点数,而不仅仅是整数,所以我会这样做:
l = []
for t in s.split():
try:
l.append(float(t))
except ValueError:
pass
请注意,这里发布的其他一些解决方案不适用于负数:
>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string -30')
['42', '32', '30']
>>> '-3'.isdigit()
False
此答案还包含数字在字符串中为浮点数的情况
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)
为了捕捉不同的模式,使用不同的模式进行查询是有帮助的。
设置所有捕获感兴趣的不同数字模式的模式:
找到逗号,例如12,300或12,300.00
r'[\d]+[.,\d]+'
查找浮点数,例如0.123或。123
r'[\d]*[.][\d]+'
求整数,例如123
r'[\d]+'
与pipe(|)组合成一个具有多个或条件的模式。
(注意:先放复杂的模式,否则简单的模式将返回复杂捕获的块,而不是复杂捕获返回完整的捕获)。
p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
下面,我们将用re.search()确认一个模式,然后返回一个可迭代的捕获列表。最后,我们将使用括号符号打印每个catch,以从匹配对象中选择匹配对象的返回值。
s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
if re.search(p, s) is not None:
for catch in re.finditer(p, s):
print(catch[0]) # catch is a match object
返回:
33
42
32
30
444.4
12,001
我发现的最干净的方法是:
>>> data = 'hs122 125 &55,58, 25'
>>> new_data = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in data)
>>> numbers = [i for i in new_data.split()]
>>> print(numbers)
['122', '125', '55', '58', '25']
或:
>>> import re
>>> data = 'hs122 125 &55,58, 25'
>>> numbers = re.findall(r'\d+', data)
>>> print(numbers)
['122', '125', '55', '58', '25']