Python:如何识别字符串中的十进制数?

2024-06-11 06:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如何识别字符串列表中的十进制数以删除它们?理想情况下,在单个操作中,content = [x for x in content if not x.isdecimal()]

(遗憾的是,isdecimal()和isnumeric()在这里不起作用)

例如,如果content = ['55', 'line', '0.04', 'show', 'IR', '50.5', 'find', 'among', '0.06', 'also', 'detected', '0.05', 'ratio', 'fashion.sense', '123442b']我希望输出是content = ['line', 'show', 'IR', 'find', 'among', 'also', 'detected', 'ratio', 'fashion.sense', '123442b']


Tags: 字符串列表irshowlinecontentfindalso
2条回答

应使用正则表达式测试字符串是否为十进制:

import re
content = ['line', '0.04', 'show', 'IR', '50.5', 'find', 'among', '0.06', 'also', 'detected', '0.05', 'ratio', 'fashion.sense', '123442b']
regex = r'^[+-]{0,1}((\d*\.)|\d*)\d+$'
content = [x for x in content if re.match(regex, x) is None]
print(content)
# => ['line', 'show', 'IR', 'find', 'among', 'also', 'detected', 'ratio', 'fashion.sense', '123442b']

只需添加Mr Geek答案,您还应该查看Regex上的python文档。在

相关问题 更多 >