Python过滤数字的4种实用方法与strip技巧
本文介绍在Python中从混合列表或字符串中过滤数字的多种方法。包括使用正则表达式匹配非纯数字项、利用try-except捕获类型转换异常、调用string内置方法判断字符属性,以及使用strip去除两端数字。此外,还展示了filter结合str.isdigit/isalpha/isalnum保留特定字符类型的技巧,适用于数据处理与清洗场景。
Python过滤数字方法概述
本文汇总了Python中实现简易过滤和删除数字的几种常见方法,供读者参考学习。
当需要从一个包含数字、汉字和字母的列表中,筛选出仅包含非纯数字的字符时,虽然可以使用正则表达式,但实现过程较为繁琐。这里介绍一种更巧妙的替代方案。
使用正则表达式过滤
方法一:使用正则表达式处理
import re
L = [u'小明', 'xiaohong', '12', 'adf12', '14']
for i in range(len(L)):
if re.findall(r'^[^\d]\w+',L[i]):
print re.findall(r'^\w+$',L[i])[0]
elif isinstance(L[i],unicode):
print L[I]
通过异常处理过滤
方法二:巧妙避开正则表达式
L = [ 'xiaohong', '12', 'adf12', '14',u'晓明']
for x in L:
try:
int(x)
except:
print x
利用string内置方法
方法三:利用string内置方法
L = [ 'xiaohong', '12', 'adf12', '14',u'晓明']
#对于python3来说同样还可以使用string.isnumeric()方法
for x in L:
if not x.isdigit():
print x
使用strip去除两端数字
方法四:去除字符串两端的数字
如果目标仅是去除字符串两端可能存在的数字,可以使用内置的strip方法,具体用法如下:
In [24]: import string
In [25]: astring = '12313213215just for 32 test 1306436'
In [26]: astring.strip(string.digits)
Out[26]: 'just for 32 test '
In [27]: astring.rstrip(string.digits)
Out[27]: '12313213215just for 32 test '
In [30]: astring.lstrip(string.digits)
Out[30]: 'just for 32 test 1306436'
#注意
In [31]: astring
Out[31]: '12313213215just for 32 test 1306436'
In [32]: astring.strip('0123456')
Out[32]: 'just for 32 test '
在.strip([char])中,当指定了char参数时,该方法会截取两端的字符,直到遇到不在set(char)集合中的字符为止。参数无需按顺序排列,需注意这一点。
filter函数的高级应用
实例扩展:
crazystring = 'dade142.!0142f[., ]ad'
# 只保留数字
new_crazy = filter(str.isdigit, crazystring)
print(''.join(list(new_crazy))) #输出:1420142
# 只保留字母
new_crazy = filter(str.isalpha, crazystring)
print(''.join(list(new_crazy))) #睡出:dadefad
# 只保留字母和数字
new_crazy = filter(str.isalnum, crazystring)
print(''.join(list(new_crazy))) #输出:dade1420142fad
# 如果想保留数字0-9和小数点'.' 则需要自定义函数
new_crazy = filter(lambda ch: ch in '0123456789.', crazystring)
print(''.join(list(new_crazy))) #输出:142.0142.
上述代码的运行结果如下:
1420142 dadefad dade1420142fad 142.0142.
以上就是关于Python如何过滤数字的详细介绍。更多相关Python过滤数字的内容,建议搜索本站历史文章或继续浏览后续文章。感谢大家的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









