Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-String to Bytes conversion. Double BackSlash issue

I've got a problem. I've this string:

a=O\x8c\x90\x05\xa1\xe2!\xbe

If i use:

c=str.encode(a)

This is the result:

b'O\\x8c\\x90\\x05\\xa1\\xe2!\\xbe'

I need those double backslash to be single backslash and i really need that type of data to be BYTES. I need to return this:

c=b'0\x8c\x90\x05\xa1\xe2!\xbe'

And type(c)==bytes Any idea?

like image 865
Teo Albano Avatar asked Oct 21 '15 11:10

Teo Albano


People also ask

What does 2 backslashes mean in Python?

In Python, you use the double slash // operator to perform floor division. This // operator divides the first number by the second number and rounds the result down to the nearest integer (or whole number).


1 Answers

You can use str.decode() with encoding as unicode-escape . Then decode it back using the required encoding to get back your bytes array. Example -

c = a.decode('unicode-escape').encode('<required encoding>')

Demo -

>>> a
b'O\\x8c\\x90\\x05\\xa1\\xe2!\\xbe'
>>> c = a.decode('unicode-escape').encode('ISO-8859-1')
>>> c
b'O\x8c\x90\x05\xa1\xe2!\xbe'
like image 58
Anand S Kumar Avatar answered Oct 09 '22 05:10

Anand S Kumar