2014-02-22 60 views
0

我想,如果列表中的一个元素包含一个单引号(')插入字符的字符串列表中的一个元素在python

例如,如果我有一个列表中插入一个反斜杠(\)如:

argList = ['AttributeError: 'tuple' object has no attribute 'rstrip'', 'SyntaxError: invalid syntax'] 

我希望能够把它转化到:

newArgList = ['AttributeError: \'tuple\' object has no attribute \'rstrip\'', 'SyntaxError: invalid syntax'] 

我会怎么做呢?

到目前为止,我有这个作为代码

for i in argList: 
    if any("\'" in elem for elem in argList): 

我只是想追加一个单引号如果一个元素有一个撇号作为子

+0

这不是附加反斜杠;附加反斜杠会在字符串的末尾添加一个反斜杠。另外,你实际上不能有一个看起来像这样的列表。如果你打印列表和列表的类型,你能告诉我们你会得到什么吗? – user2357112

+0

我想不出有什么好的理由让你这么做,我建议你查看关于字符串的Python教程:http://docs.python.org/2/tutorial/introduction.html#strings –

回答

1

如果你有串

s = "AttributeError: 'tuple' object has no attribute 'rstrip'" 

您可以使用replace(old, new)方法:

s.replace("'", "\\'") 

请记住,\需要是escaped,因为它是一个特殊字符。

相关问题