如何删除' \'从Python中的列表

时间:2015-05-18 06:29:58

标签: python

当我有两个以' \'开头的项目时在列表中。我不能删除第二个。在这种情况下' \ x80'我尝试了一切但都没有成功。

s = ['a', 'b' , 'c' , '\xe2 ','\x80', 'd', 'f', 'g']

if x == '\x2' or x == '\80' :
    s.remove(x)

print s

我得到:['a', 'b', 'c','\x80', 'd', 'f','g']

有什么想法吗?

由于

4 个答案:

答案 0 :(得分:1)

这是一个简单的修复。删除ascii值大于125(})的所有字符:

s = ['a', 'b' , 'c' , '\xe2','\x80', 'd', 'f', 'g']

s = [i for i in s if ord(i) < 126]   # keep only characters with ascii value less that 126

DEMO

答案 1 :(得分:0)

import re
s = ['a', 'b' , 'c' , '\xe2 ','\x80', 'd', 'f', 'g']
print [i for i in s if  re.match(r"^[a-zA-Z0-9]+",i)]

答案 2 :(得分:0)

您可以使用字符串库(请参阅documentation页面):

import string

s = ['a', 'b' , 'c' , '\xe2 ','\x80', 'd', 'f', 'g']
cleaned = [x for x in s if x in string.printable]

答案 3 :(得分:0)

s = ['a', 'b' , 'c' , '\xe2 ','\x80', 'd', 'f', 'g']
clean_list = []

for i in s:
   if '/' not in i:
      clean_list.append(i)