假设我有一根绳子
string1 = "498results should get"
现在我只需要从字符串中获取整数值,如
498
。 在这里我不想使用 list slicing
因为整数值可能会像下面的例子一样增加:
string2 = "49867results should get"
string3 = "497543results should get"
所以我只想以完全相同的顺序从字符串中获取整数值。 我的意思是分别来自
498,49867,497543
的 string1,string2,string3
。
任何人都可以让我知道如何用一两行代码完成此操作吗?
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
如果字符串中有多个整数:
>>> list(map(int, re.findall(r'\d+', string1)))
[498]
来自ChristopheD的答案:https://stackoverflow.com/a/2500023/1225603
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
这是您的一句台词,不使用任何正则表达式,有时可能会很昂贵:
>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))
返回:
'123453120'
如果您有多组数字,那么这是另一种选择
>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']
但它对于浮点数字符串没有好处。
迭代器版本
>>> 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)))
在 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]
integerstring=""
string1 = "498results should get"
for i in string1:
if i.isdigit()==True
integerstring=integerstring+i
print(integerstring)
def function(string):
final = ''
for i in string:
try:
final += str(int(i))
except ValueError:
return int(final)
print(function("4983results should get"))
另一种选择是使用
rstrip
和 string.ascii_lowercase
删除尾随字母(以获取字母):
import string
out = [int(s.replace(' ','').rstrip(string.ascii_lowercase)) for s in strings]
输出:
[498, 49867, 497543]