说我有一个字符串
"There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
我希望能够将数字动态提取到列表中:[34, 0, 4, 5]
.
有没有一种简单的方法可以在 Python 中做到这一点?
换句话说,
有没有办法提取由任何分隔符分隔的连续数字簇?
当然,使用正则表达式:
>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> import re
>>> list(map(int, re.findall(r'[0-9]+', s)))
[34, 0, 4, 5]
您也可以在没有正则表达式的情况下执行此操作,尽管它需要更多的工作:
>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> #replace nondigit characters with a space
... s = "".join(x if x.isdigit() else " " for x in s)
>>> print s
34 0 4 5
>>> #get the separate digit strings
... digitStrings = s.split()
>>> print digitStrings
['34', '0', '4', '5']
>>> #convert strings to numbers
... numbers = map(int, digitStrings)
>>> print numbers
[34, 0, 4, 5]