【发布时间】:2016-12-09 21:08:34
【问题描述】:
为了回答this question,我设法通过转义反斜杠将字符串转义为print。
当我试图概括它以转义所有转义字符时,它似乎什么都不做:
>>> 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等。
【问题讨论】:
-
您的字符串中没有文字反斜杠可以匹配。 literal 包含两个字符序列
\n以 指定 换行符,但 Python 将其转换为生成的str对象中的单个文字换行符。