简体   繁体   中英

decode(unicode_escape) in python 3 a string

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM