Python-String to Bytes conversion. Double BackSlash issue [duplicate]
Asked Answered
K

1

14

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?

Katzir answered 21/10, 2015 at 11:14 Comment(2)
what does print(repr(a)) give?Goldsworthy
Sry. This: 'O\\x8c\\x90\\x05\\xa1\\xe2!\\xbe'Katzir
G
22

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'
Goldsworthy answered 21/10, 2015 at 11:23 Comment(5)
Nvm. didn't notice c is Bytes.Katzir
Still not getting what i want. I need this output --> c=b'0\x8c\x90\x05\xa1\xe2!\xbe' Your solution gives me this: b'O\xc2\x8c\xc2\x90\x05\xc2\xa1\xc3\xa2!\xc2\xbe'Katzir
Thats because \xe2 is not valid utf-8 . Use a valid encoding and it should workGoldsworthy
@TeoAlbano Check now, using ISO-8859-1 should work.Goldsworthy
You are a GOD. If you are dumping and data via DUMP in Redis and you're trying to RESTORE it, you will absolutely need to decode, then encode it back using ISO-8859-1.Abacus

© 2022 - 2024 — McMap. All rights reserved.