Replace a character with backslash bug - Python

冷暖自知 提交于 2019-12-30 08:32:14

问题


This feels like a bug to me. I am unable to replace a character in a string with a single backslash:

>>>st = "a&b"
>>>st.replace('&','\\')
'a\\b'

I know that '\' isn't a legitimate string because the \ escapes the last '. However, I don't want the result to be 'a\\b'; I want it to be 'a\b'. How is this possible?


回答1:


You are looking at the string representation, which is itself a valid Python string literal.

The \\ is itself just one slash, but displayed as an escaped character to make the value a valid Python literal string. You can copy and paste that string back into Python and it'll produce the same value.

Use print st.replace('&','\\') to see the actual value being displayed, or test for the length of the resulting value:

>>> st = "a&b"
>>> print st.replace('&','\\')
a\b
>>> len(st.replace('&','\\'))
3


来源:https://stackoverflow.com/questions/17300917/replace-a-character-with-backslash-bug-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!