Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 regex on bytes variable [duplicate]

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)
like image 655
wasp256 Avatar asked Jun 09 '17 12:06

wasp256


2 Answers

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)
like image 140
Dimitris Fasarakis Hilliard Avatar answered Nov 16 '22 08:11

Dimitris Fasarakis Hilliard


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'
like image 6
Martijn Pieters Avatar answered Nov 16 '22 07:11

Martijn Pieters