在python 3中解码(unicode_escape)一个字符串

Tim*_*mmy 2 python escaping

我已经检查了此解决方案,但在python3中不起作用。

我有一个这样的转义字符串:str = "Hello\\nWorld"而且我想获得未转义的相同字符串:str_out = Hello\nWorld

我尝试了这个没有成功: AttributeError: 'str' object has no attribute 'decode'

这是我的示例代码:

str = "Hello\\nWorld"
str.decode('unicode_escape')
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 6

decode适用于bytes,您可以通过对字符串进行编码来创建。

我会编码(使用默认值),然后使用unicode-escape

>>> s = "Hello\\nWorld"
>>> s.encode()
b'Hello\\nWorld'
>>> s.encode().decode("unicode-escape")
'Hello\nWorld'
>>> print(s.encode().decode("unicode-escape"))
Hello
World
>>> 
Run Code Online (Sandbox Code Playgroud)