铸造原始字符串python

dav*_*ave 33 python string

给定一个包含字符串的变量是否可以快速将其转换为另一个原始字符串变量?

以下代码应说明我所追求的内容:

line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"

print(line1 == line2)  # outputs False
print(("%r"%line1)[1:-1] == line2)  # outputs True
Run Code Online (Sandbox Code Playgroud)

到目前为止我找到的最接近的是%r格式化标志,它似乎返回一个原始字符串,尽管在单引号内.有没有更简单的方法来做这种事情?

Ign*_*ams 64

Python 3:

"hurr..\n..durr".encode('unicode-escape').decode()
Run Code Online (Sandbox Code Playgroud)

Python 2:

"hurr..\n..durr".encode('string-escape')
Run Code Online (Sandbox Code Playgroud)

  • @Erik,Python 3中的字符串是Unicode,使用`unicode-escape`. (18认同)
  • 我在Python3.3 LookupError中遇到错误:未知编码:string-escape (7认同)
  • 好一个.str.encode()与各种编解码器正是我所追求的.'unicode-escape'实际上解决了我也遇到的另一个问题.干杯 (6认同)
  • 这不适用于 `\w` 等。 (3认同)