从列表中的字符串中删除“

时间:2018-12-04 10:51:10

标签: python list loops for-loop

我正在尝试删除或忽略字符串列表中的'符号(撇号)。我不知道我的for循环是否完全是错误的?

n = ["a", "a's", "aa's"] #example list

for i in n:
    i.strip("'")

2 个答案:

答案 0 :(得分:1)

strip在这里无法使用replace

In [9]: [i.replace("'",'') for i in lst]
Out[9]: ['a', 'as', 'aas']

答案 1 :(得分:1)

这里有两个问题。

  • 首先,strip在字符串中间无效,您必须使用`replace(“'”,“”)
  • 第二个,更重要的是,字符串是不可变的。即使i.strip(...)做了您想要的,它也不会更改 i。它只会产生一个新的字符串。因此,您必须存储该字符串。

总结,尝试类似

n = [i.replace("'", "") for i in n]