无法在字符串中转义转义字符

时间:2016-12-09 21:08:35

标签: python string escaping

为了回答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

1 个答案:

答案 0 :(得分:2)

使用r'text'将字符串定义为raw,如下面的代码所示:

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