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')
Python 3 - String decode() MethodThe decode() method decodes the string using the codec registered for encoding. It defaults to the default string encoding.
decode() is a method specified in Strings in Python 2. This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.
The encoding `unicode_escape` is not about escaping unicode characters. It's about python source code. It's defined as: > Encoding suitable as the contents of a Unicode literal in ASCII-encoded Python source code, except that quotes are not escaped.
If you have a specific single character (like '\n' ) you need to un-escape, like I had, you can just do s. replace('\\n', '\n) .
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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With