【问题标题】:Can't escape escape characters in string无法转义字符串中的转义字符
【发布时间】: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 对象中的单个文字换行符。

标签: python string escaping


【解决方案1】:

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

【讨论】:

  • 原始字符串正是我想要的,谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-09-14
  • 2018-05-10
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 2014-03-17
  • 2016-04-15
  • 1970-01-01
相关资源
最近更新 更多