Python Can';t在字符串中转义转义字符

Python Can';t在字符串中转义转义字符,python,string,escaping,Python,String,Escaping,在尝试回答时,我通过对反斜杠进行转义,成功地使字符串打印转义字符 当我尝试对其进行泛化以转义所有转义字符时,它似乎什么也不做: >>> a = "word\nanother word\n\tthird word" >>> a 'word\nanother word\n\tthird word' >>> print a word another word third word >>> b = a.replace

在尝试回答时,我通过对反斜杠进行转义,成功地使字符串
打印
转义字符

当我尝试对其进行泛化以转义所有转义字符时,它似乎什么也不做:

>>> 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
但对于特定转义字符,同样的方法也能起作用:

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

有没有一个通用的方法来实现这一点?应包括
\n
\t
\r
等。

使用r'text'将字符串定义为原始字符串,如以下代码所示:

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

字符串中没有要匹配的文字反斜杠。文本包含两个字符的序列
\n
以指定换行符,但Python将其转换为结果
str
对象中的单个文本换行符。原始字符串正是我要查找的,谢谢!