I need to convert a string with bytes (string view) to byte object in Python.
string = input() # string = '\xff\x00B'bs = samefunc(string) # typeof(bs) == bytes, len(bs) == 3
print(bs[0]) # b'\xff'
print(bs[1]) # b'\x00'
print(bs[2]) # b'B'
In my app the string input is so large the self parser will be very slow.
You can use eval
(or ast.literal_eval
, which is more secure if the input is not 100% in your hands):
s = input() # s = '\\xff\\x00B'
bs = eval("b'%s'" % s) # typeof(bs) == bytes, len(bs) == 3
print(bs[0]) # 255
print(bs[1]) # 0
print(bs[2]) # 66