0

In python3 I have a byte object like

a = b'\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\\xff\\xdb\\x00C\\x00\\x08\\x06\\x06\\x07\\x06\\x05\\x08\\x07\\x07\\x07\\t\\t\\x08\\n\\x0c\\x14\\r\\x0c\\x0b\\x0b\\x0c\\x19\\x12\\x13\\x0f\\x14\\x1d\\x1a\\x1f\\x1e\\x1d\\x1a\\x1c\\x1c $.\\\' ",#\\x1c\\x1c(7),01444\\x1f\\\'9=82<.342\\xff\\xdb\\x00C\\x01\\t\\t\\t\\x0c\\x0b\\x0c\\x18\\r\\r\\x182!'

and I would like replace all double backslashes with single backslash

d = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.\\\' ",#\x1c\x1c(7),01444\x1f\\\'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!'
wjandrea
  • 28,235
  • 9
  • 60
  • 81
rahram
  • 560
  • 1
  • 7
  • 21
  • https://stackoverflow.com/questions/38763771/how-do-i-remove-double-back-slash-from-a-bytes-object – herisson Jan 19 '21 at 20:13
  • 1
    Does this answer your question? [How do I remove double back slash (\`\\‌\`) from a bytes object?](https://stackoverflow.com/questions/38763771/how-do-i-remove-double-back-slash-from-a-bytes-object) – Tomerikoo Apr 12 '21 at 19:50
  • @herisson If you think this question has an answer somewhere else in this site - [flag it as duplicate](https://stackoverflow.com/help/privileges/flag-posts) instead of posting a link as a comment... – Tomerikoo Apr 12 '21 at 19:52
  • You seem to have an extra `\x1c!` in the output – wjandrea Apr 12 '21 at 21:24

1 Answers1

2

Simply use the unicode_escape text encoding to decode it into a string, then use the raw_unicode_escape codec to make it back into a bytes string.

escaped_byte_literal = b'\\xff\\xd8\\xff'
byte_literal.decode('unicode_escape').encode('raw_unicode_escape')

This code will return an unescaped byte literal, which provides you with the desired result: b'\xff\xd8\xff'. The unicode_escape codec decodes, removing the escapes, and the raw_unicode_escape codec encodes without adding escapes.

Darrius
  • 313
  • 2
  • 14