Python3 regex on bytes variable [duplicate]

被刻印的时光 ゝ 提交于 2021-02-07 13:37:52

问题


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)

回答1:


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)



回答2:


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'


来源:https://stackoverflow.com/questions/44457455/python3-regex-on-bytes-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!