这个字符串中没有斜杠或反斜杠。 反斜杠被用来转义引号 '
, 尽管它们不必这样做,因为该字符串是用 ""
包围的。
print("I don\'t know why I don\'t have the right answer")
print("I don't know why I don't have the right answer")
生成:
I don't know why I don't have the right answer
I don't know why I don't have the right answer
此外,您使用了错误的字符,而且
strip
仅从字符串的两端移除字符。
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
>>> print("///I don't know why ///I don't have the right answer///".strip("/"))
I don't know why ///I don't have the right answer
为了在字符串中插入反斜杠,您需要对其进行转义(或使用原始字符串文字)。
>>> print("\\I don't know why ///I don't have the right answer\\".strip("/"))
\I don't know why ///I don't have the right answer\
正如你所看到的,即使反斜杠位于字符串开头和结尾,它们也没有被删除。
最后,为了回答原始问题。一种方法是使用字符串的 replace
方法:
>>> print("\\I don't know why \\\I don't have the right answer\\".replace("\\",""))
I don't know why I don't have the right answer
此外,感谢你在自己的答案出错后寻求正确答案的建议 =)。