python从字符串中提取数字_filter

 

my_str = '123and456'

number = filter(str.isdigit,  my_str )

# number = 123456

 使用正则表达式:

>>> import re
>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
['42', '32', '30']

这也将匹配42 bla42bla。如果您只想要按字边界(空格,句号,逗号)分隔的数字,则可以使用\ b:

>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
['42', '32', '30']

最终得到一个数字列表而不是字符串列表:

>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
[42, 32, 30]

 

 
posted @ 2019-06-14 09:59  553490191  阅读(109740)  评论(1编辑  收藏  举报