python(15)提取字符串中的数字

python 提取一段字符串中去数字

ss = “123ab45”

方法一:filter

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

str.filter:如果字符串只包含数字则返回 True 否则返回 False。

filter(str.isdigit, ss)

别处copy的filter的用法:

# one
>>> filter(str.isdigit, '123ab45')
'12345'

#two
def
not_empty(s): return s and s.strip() filter(not_empty, ['A', '', 'B', None, 'C', ' '])
# 结果: ['A', 'B', 'C'] 
# 列表中的每个元素都会过一遍 pattern,返回的还是列表

方法二:正则表达式

s = re.findall("d+",ss)[0]
print s

原文地址:https://www.cnblogs.com/lovychen/p/5550670.html