32

In Python, I have a string like this:

'\\x89\\n' 

How can I decode it into a normal string like:

'\x89\n' 
0

2 Answers 2

44

If your input value is a str string, use codecs.decode() to convert:

import codecs codecs.decode(raw_unicode_string, 'unicode_escape') 

If your input value is a bytes object, you can use the bytes.decode() method:

raw_byte_string.decode('unicode_escape') 

Demo:

>>> import codecs >>> codecs.decode('\\x89\\n', 'unicode_escape') '\x89\n' >>> b'\\x89\\n'.decode('unicode_escape') '\x89\n' 

Python 2 byte strings can be decoded with the 'string_escape' codec:

>>> import sys; sys.version_info[:2] (2, 7) >>> '\\x89\\n'.decode('string_escape') '\x89\n' 

For Unicode literals (with a u prefix, e.g. u'\\x89\\n'), use 'unicode_escape'.

Sign up to request clarification or add additional context in comments.

10 Comments

This doesn't work in python3. (str doesn't have a decode method and also string_escape isn't a valid encoding anymore).
@Bakuriu: The OP never specified a Python version.
Yeah, you're right, what I was trying to decode is a bytes class object, not a str object!
@user486005: that was crucial information; I had to assume you were using Python 2 (still the more likely option, statistically speaking). I've updated my answer to include the correct methods to use in Python 3.
@MartijnPieters I didn't know that python-3 has remove the decode method of string object then, at first I thought it was a string object while it was a bytes object indeed, so it just happens to run successfully. Thanks a lot.
|
12

This would work for Python 3:

b'\\x89\\n'.decode('unicode_escape') 

1 Comment

@user486005: I am glad it helped. It was meant as addition to the Martinj Python 2 solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.