假设我有一个字符串,比如
"There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)" 我希望能够动态地将数字提取到一个列表中:[34, 0, 4, 5]。
在Python中有没有一种简单的方法可以做到这一点?
换句话说,
有什么方法可以提取由任何分隔符分隔的连续数字簇吗?
发布于 2013-04-01 23:09:25
当然,使用regular expressions
>>> 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]发布于 2013-04-01 23:22:54
您也可以在没有正则表达式的情况下做到这一点,尽管这需要更多的工作:
>>> 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]https://stackoverflow.com/questions/15745949
复制相似问题