18

I'm trying to perform a regex substitution on a bytes variable but I receive the error

  sequence item 0: expected a bytes-like object, str found

Here is a small code example to reproduce the problem with python3:

import re

try:
    test = b'\x1babc\x07123'
    test = re.sub(b"\x1b.*\x07", '', test)
    print(test)
except Exception as e:
    print(e)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
wasp256
  • 5,943
  • 12
  • 72
  • 119

2 Answers2

25

When acting on bytes object, all arguments must be of type byte, including the replacement string. That is:

test = re.sub(b"\x1b.*\x07", b'', test)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
7

Your replacement value must be a bytes object too:

re.sub(b"\x1b.*\x07", b'', test)
#                     ^^^

You can't replace matching bytes with a str object, even if that is an empty string object.

Demo:

>>> import re
>>> test = b'\x1babc\x07123'
>>> re.sub(b"\x1b.*\x07", b'', test)
b'123'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343