Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 530
Timmy Avatar asked Feb 21 '18 14:02

Timmy


People also ask

How do I decode in Python 3?

Python 3 - String decode() MethodThe decode() method decodes the string using the codec registered for encoding. It defaults to the default string encoding.

How do you decode and encode a string in Python?

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.

What is Unicode_escape in Python?

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.

How do you unescape a string in Python?

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


1 Answers

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
>>> 
like image 159
Jean-François Fabre Avatar answered Oct 19 '22 04:10

Jean-François Fabre