2

I'm trying to convert a bytearray to and from a string. Why does the following not work? The encode seems to add an extra slash. Am I using the wrong encoding? I'm using python3.6

In [19]: b'\x88'.decode('unicode_escape') Out[19]: '\x88' In [20]: '\x88'.encode('unicode_escape') Out[20]: b'\\x88' 
0

2 Answers 2

2

When to use raw_unicode_escape mode

The backslash character is escaped so is written as \\. If you don't want that try the 'raw_unicode_escape' codec.

In the editor here, when answering your question, if I write \\ you see \ in the response so I actually had to write \\\\. Try it yourself to see what I mean (or edit this answer to see what I mean).

This is what I actually had to write above

The backslash character is escaped so is written as \\\\. If you don't want that try the 'raw_unicode_escape' codec. In the editor here, when answering your question, if I write \\\\ you see \\ in the response so I actually had to write \\\\\\\\. Try it yourself to see what I mean (or edit this answer to see what I mean). 

By escaping the backspash the unicode_escape codec guards against problems like that.

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

Comments

0

You are using here bytes not bytearray So, if you want to encode and decode keeping the '\x', you can use

'\x88'.encode('raw_unicode_escape') b'\x88'.decode('unicode_escape') 

If what you have is a single value bytearray like this:

barray = bytearray([0x88]) 

you can get the string of this byte this way:

s = format(barray[0], '02x') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.