Can't escape escape characters in string

▼魔方 西西 提交于 2019-12-18 09:37:05

问题


In an attempt to answer this question, I managed to get the string to print the escape characters by escaping the backslash.

When I try to generalize it to escape all escaped characters, it seems to do nothing:

>>> a = "word\nanother word\n\tthird word"
>>> a
'word\nanother word\n\tthird word'
>>> print a
word
another word
        third word
>>> b = a.replace("\\", "\\\\")
>>> b
'word\nanother word\n\tthird word'
>>> print b
word
another word
        third word

but this same method for specific escape characters, it does work:

>>> b = a.replace('\n', '\\n')
>>> print b
word\nanother word\n    third word
>>> b
'word\\nanother word\\n\tthird word'

Is there a general way to achieve this? Should include \n, \t, \r, etc.


回答1:


Define your string as raw using r'text', like in the code below:

a = r"word\nanother word\n\tthird word"
print(a)
word\nanother word\n\tthird word

b = "word\nanother word\n\tthird word"
print(b)
word
another word
        third word


来源:https://stackoverflow.com/questions/41068918/cant-escape-escape-characters-in-string

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