无法通过regex从python3中的字节中删除字符串

时间:2015-08-09 05:35:06

标签: python regex tornado python-3.4

*我在python 3中使用re.sub时出错 **我的代码是:

 chunk = re.sub(b'-----------------------------(.+)--\r\n', '', chunk 

我有这个错误:

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

它在python2中工作,但在python3.4中不起作用。 另外我使用tornadofreamwork 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

替换部分也必须是字节字符串。

chunk = re.sub(b'-----------------------------(.+)--\r\n', b'', chunk)

示例:

>>> chunk = b'-----------------------------5313032314004\r\nContent-Disposition: form-data; name="file"; filename="4.jpg"\r\nContent-Type: image/jpeg\r\n\r\n\xff\xd8\xff'
>>> re.sub(b'-', b'', chunk)
b'5313032314004\r\nContentDisposition: formdata; name="file"; filename="4.jpg"\r\nContentType: image/jpeg\r\n\r\n\xff\xd8\xff'