在 Python 中如何从字符串中获取整数值?

假设我有一根绳子

string1 = "498results should get"

现在我只需要从字符串(如 498)中获取整数值。这里我不想使用 list slicing,因为整数值可能会像下面的例子一样增加:

string2 = "49867results should get"
string3 = "497543results should get"

所以我只想从字符串中得到整数值,顺序完全相同。我的意思是像 498,49867,497543string1,string2,string3分别。

有人能用一两句话告诉我怎么做吗?

248975 次浏览
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498

如果字符串中有多个整数:

>>> map(int, re.findall(r'\d+', string1))
[498]

迭代器版本

>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]
>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))

来自 克里斯托弗的答案: https://stackoverflow.com/a/2500023/1225603

r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789

如果你有多组数字,那么这是另一个选项

>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']

但是它对浮点数字字符串没有好处。

这是你的一行程序,没有使用任何正则表达式,有时会变得昂贵:

>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))

报税表:

'123453120'
def function(string):
final = ''
for i in string:
try:
final += str(int(i))
except ValueError:
return int(final)
print(function("4983results should get"))

对于 python 3.6,这两行返回一个列表(可能为空)

>>[int(x) for x in re.findall('\d+', your_string)]

类似

>>list(map(int, re.findall('\d+', your_string))

这种方法使用列表内涵,只需将字符串作为参数传递给函数,它就会返回该字符串中的整数列表。

def getIntegers(string):
numbers = [int(x) for x in string.split() if x.isnumeric()]
return numbers

像这样

print(getIntegers('this text contains some numbers like 3 5 and 7'))

输出

[3, 5, 7]

另一个选择是使用 rstripstring.ascii_lowercase删除尾随的字母(以获得字母) :

import string
out = [int(s.replace(' ','').rstrip(string.ascii_lowercase)) for s in strings]

产出:

[498, 49867, 497543]
  integerstring=""
string1 = "498results should get"
for i in string1:
if i.isdigit()==True
integerstring=integerstring+i
print(integerstring)