为了回答这个问题,我设法print通过转义反斜杠来使字符串成为转义字符。
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,等。
\n
\t
\r
使用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