如何从字符串中删除除数字以外的所有字符?
3 回答

皈依舞
TA贡献1851条经验 获得超3个赞
使用re.sub,如下所示:
>>> import re
>>> re.sub("\D", "", "aas30dsa20")
'3020'
\D 匹配任何非数字字符,因此,上面的代码实质上是将每个非数字字符替换为空字符串。
或者,您可以filter像这样使用(在Python 2k中):
>>> filter(lambda x: x.isdigit(), "aas30dsa20")
'3020'
由于在Python 3k中,filter返回的是迭代器而不是list,因此您可以使用以下代码:
>>> ''.join(filter(lambda x: x.isdigit(), "aas30dsa20"))
'3020'

ibeautiful
TA贡献1993条经验 获得超5个赞
您可以使用过滤器:
filter(lambda x: x.isdigit(), "dasdasd2313dsa")
在python3.0上,您必须加入这个(有点丑陋的:()
''.join(filter(lambda x: x.isdigit(), "dasdasd2313dsa"))
添加回答
举报
0/150
提交
取消