我只需要过滤掉只包含数字和/或一组标点符号的字符串。过滤掉只包含数字和/或标点符号的字符串 - python
我试着检查每个字符,然后总结布尔条件来检查它是否等于len(str)
。有没有一种更Python的方式来做到这一点:
>>> import string
>>> x = ['12,523', '3.46', "this is not", "foo bar 42", "23fa"]
>>> [i for i in x if [True if j.isdigit() else False for j in i] ]
['12,523', '3.46', 'this is not', 'foo bar 42']
>>> [i for i in x if sum([True if j.isdigit() or j in string.punctuation else False for j in i]) == len(i)]
['12,523', '3.46']
你确定你没有**真的意思是“我需要找到可能代表数字的字符串,但是”漂浮“等不起作用,因为我也想让逗号作为数千个分隔符”? –
是的,我会稍后需要,但两层过滤也将捕获合法文件中的数字索引(例如'x = [“chapter”,“1.2.3.5”]') – alvas