alyssaeliyah
alyssaeliyah

Reputation: 2244

Python Convert class<str> to class <bytes>

I have this string value with class :

key = "b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'"

I want it to convert to with class

key = b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'

How will I do it in Python? Any would be very much appreciated.

Upvotes: 1

Views: 790

Answers (2)

blhsing
blhsing

Reputation: 106946

If the value of your key variable is literally "b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'" (rather than r"b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'" that @Jean-FrançoisFabre's answer presumes), you can use int.to_bytes to convert the characters in key to bytes after stripping the first two and the last characters (which are b' and '):

b''.join(ord(c).to_bytes(1, 'big') for c in key[2:-1])

This returns:

b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

the provider of key should be fixed to store the value and not the representation of the bytes

Anyway, to undo that, you can use the reverse, which is ast.literal_eval

import ast

key = r"b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'"
print(ast.literal_eval(key))

which prints:

b'\x81*u\x11\xe8k\xef\xbc\xc6\xef\x9d\x83\x9f!\x0ej'

note that I had to use the raw prefix on the key bytes literal, which probably matches the input data you have.

This fix doesn't replace a proper fix of the whole chain: converting to representation and parsing it back has a cost CPU-wise.

Upvotes: 2

Related Questions