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)
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)
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With