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

发布于 2021-01-29 15:04:40

为了回答这个问题,我设法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,等。

关注者
0
被浏览
89
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看