我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
对于电话号码,您可以在regex中排除所有带\D的非数字字符:
import re
phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)
r"\D"中的r代表原始字符串。这是必要的。如果没有它,Python将把\D视为转义字符。
其他回答
我只是添加这个答案,因为没有人添加一个使用异常处理,因为这也适用于浮动
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]
如果你只想提取正整数,试试下面的方法:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
我认为这比正则表达式示例更好,因为您不需要另一个模块,而且它更具可读性,因为您不需要解析(和学习)正则表达式迷你语言。
这将不识别浮点数、负整数或十六进制格式的整数。如果您不能接受这些限制,下面jmnas的答案可以解决问题。
对于电话号码,您可以在regex中排除所有带\D的非数字字符:
import re
phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)
r"\D"中的r代表原始字符串。这是必要的。如果没有它,Python将把\D视为转义字符。
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中找到的数字添加到该列表中。
我一直在寻找一个解决方案来去除字符串的面具,特别是从巴西的电话号码,这篇文章没有回答,但启发了我。这是我的解决方案:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'