decode(unicode_escape) in python 3 a string

放肆的年华 提交于 2020-04-06 11:23:09

问题


I've checked this solution but it doesn't work in python3.

I've an escaped string of this kind: str = "Hello\\nWorld" and I want to obtain the same string unescaped: str_out = Hello\nWorld

I tried with this without succes: AttributeError: 'str' object has no attribute 'decode'

Here my sample code:

str = "Hello\\nWorld"
str.decode('unicode_escape')

回答1:


decode applies to bytes, which you can create by encoding from your string.

I would encode (using default) then decode with 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
>>> 


来源:https://stackoverflow.com/questions/48908131/decodeunicode-escape-in-python-3-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!