Shi*_*dla 47 python string integer
假设我有一个字符串
string1 = "498results should get"
Run Code Online (Sandbox Code Playgroud)
现在我只需要从字符串中获取整数值498.在这里我不想使用,list slicing因为整数值可能像这些例子一样增加:
string2 = "49867results should get"
string3 = "497543results should get"
Run Code Online (Sandbox Code Playgroud)
所以我想从字符串中只得到完全相同的顺序的整数值.我的意思是分别498,49867,497543来自string1,string2,string3.
任何人都可以让我知道如何在一两行中做到这一点?
jam*_*lak 95
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
Run Code Online (Sandbox Code Playgroud)
如果字符串中有多个整数:
>>> map(int, re.findall(r'\d+', string1))
[498]
Run Code Online (Sandbox Code Playgroud)
Sep*_*ero 38
这是ChristopheD的答案:https://stackoverflow.com/a/2500023/1225603
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
Run Code Online (Sandbox Code Playgroud)
jac*_*ury 14
如果你有多组数字,那么这是另一种选择
>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']
Run Code Online (Sandbox Code Playgroud)
但它对浮点数字符串没有好处.
迭代器版本
>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]
Run Code Online (Sandbox Code Playgroud)
这是你的单行,不使用任何正则表达式,有时会变得昂贵:
>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))
Run Code Online (Sandbox Code Playgroud)
收益:
'123453120'
Run Code Online (Sandbox Code Playgroud)
>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))
Run Code Online (Sandbox Code Playgroud)