我正在尝试对字节变量执行正则表达式替换但我收到错误
sequence item 0: expected a bytes-like object, str found
这是一个用python3重现问题的小代码示例:
import re
try:
test = b'\x1babc\x07123'
test = re.sub(b"\x1b.*\x07", '', test)
print(test)
except Exception as e:
print(e)
答案 0 :(得分:2)
当对bytes对象执行操作时,所有参数必须是byte
类型,包括替换字符串。那就是:
test = re.sub(b"\x1b.*\x07", b'', test)
答案 1 :(得分:1)
您的替换值也必须是bytes
对象:
re.sub(b"\x1b.*\x07", b'', test)
# ^^^
您无法用str
对象替换匹配的字节,即使这是一个空字符串对象。
演示:
>>> import re
>>> test = b'\x1babc\x07123'
>>> re.sub(b"\x1b.*\x07", b'', test)
b'123'