Python从列表中删除特定字符串

时间:2015-04-08 21:52:52

标签: python

我想删除此列表中包含字母或具有特殊字符的任何字符串。

test = ["1.0","2.0","3","asdf","1.0f","1f","@#$aa1", "4"]

我想要的结果是带有这些的新列表。

newTest = ["1.0","2.0","3", "4"]

3 个答案:

答案 0 :(得分:0)

您可以使用re.match

>>> import re
>>> [i for i in test if re.match(r'^[\d.]+$',i)]
['1.0', '2.0', '3', '4']

r'^[\d.]+$'只会匹配长度为1或更长的点和数字的任意组合。

答案 1 :(得分:0)

如果您只想要数字,可以执行以下操作:

def try_parse(s):
  try:
    f = float(s)
    return 1
  except ValueError:
    return 0

test = ["1.0","2.0","3","asdf","1.0f","1f","@#$aa1", "4"]

t2 = [i for i in test if try_parse(i)==1]
print(t2)

给你:

['1.0', '2.0', '3', '4']

如果您希望它们直接浮动:

def try_parse(s):
  try:
    return float(s)
  except ValueError:
    return 'error'

test = ["1.0","2.0","3","asdf","1.0f","1f","@#$aa1", "4"]

t2 = [try_parse(i) for i in test if try_parse(i)!='error']
print(t2)

给出:

[1.0, 2.0, 3.0, 4.0]

答案 2 :(得分:0)

使用try块而不是正则表达式可能更容易:

newTest = []

for i in test:
    try:
        float(i) # numeric
        newTest.append(i)

    except:
        pass