I have a string

s = "b'\\xff\\xd8\\xff\\xe0\\x00'" 

You need to get it in bytes, ie:

 b = b'\xff\xd8\xff\xe0\x00' type(b) = bytes 

How to do it?

  • one
    Taki "b'\xff\xd8\xff\xe0\x00'" or "b'\\xff\\xd8\\xff\\xe0\\x00'" ? - andreymal
  • one
    print (s) = "b '\ xff \ xd8 \ xff \ xe0 \ x00'", means s = "b '\\ xff \\ xd8 \\ xff \\ xe0 \\ x00'" - Oleg Since
  • you should find the place that this line spawned and correct it so that the bytes themselves are output, and not their textual representation. - jfs

1 answer 1

You can use the ast magic module:

 s = "b'\\xff\\xd8\\xff\\xe0\\x00'" print(repr(s), type(s)) import ast b = ast.literal_eval(s) print(repr(b), type(b)) 

Console:

 "b'\\xff\\xd8\\xff\\xe0\\x00'" <class 'str'> b'\xff\xd8\xff\xe0\x00' <class 'bytes'>