filter digit number in string

本文介绍了几种在Python中从字符串中提取数字的方法。利用正则表达式和内置函数filter,可以高效地移除非数字字符,仅保留数字部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://stackoverflow.com/questions/1450897/python-removing-characters-except-digits-from-string

 

import re 
re.sub("/D", "", "aas30dsa20") 
'3020' 

 

/D matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.

 

Or you can use filter, like so (in Python 2k):

filter(lambda x: x.isdigit(), "aas30dsa20") 

Since in Python 3k, filter returns an iterator instead of a list, you can use the following instead:

>>> ''.join(filter(lambda x: x.isdigit(), "aas30dsa20")) 
'3020' 


s=''.join(i for i in s if i.isdigit()) 

Another generator variant.

 

>>> s = "foo200bar" 
>>> new_s = "".join(i for i in s if i in "0123456789") 

 

>>> text = "9jk78k.9k87h.ji09j9oj" 
>>> print "".join(i for i in text if i in ".0123456789").replace(".",",",1).replace(".","").replace(",",".") 
978.987099 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值