【问题标题】:can't remove a string from bytes in python3 by regex无法通过正则表达式从 python3 中的字节中删除字符串
【发布时间】:2015-08-09 05:35:06
【问题描述】:

*我在 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 请帮我解决这个问题。

【问题讨论】:

    标签: python regex tornado python-3.4


    【解决方案1】:

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

    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'
    

    【讨论】:

    • 不!当我在 string 之前使用 r 时,会发生此错误::::can't use a string pattern on a bytes-like object
    • chunk = b'-----------------------------5313032314004\r\nContent-Disposition: form -数据;名称=“文件”; filename="4.jpg"\r\nContent-Type: image/jpeg\r\n\r\n\xff\xd8\xff\........行动,我尝试删除'--- ---------5313032514004\r\n 从它
    • 正好块是文件的一部分,我是从 Ajax 的表单中收到的
    • @seydimanfeyzbakhsh 替换部分必须是字节字符串。检查我的更新。
    • @Avinash Raj:我尝试 b'-----...' 但不起作用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2021-09-07
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2021-01-17
    • 2014-06-20
    • 1970-01-01
    相关资源
    最近更新 更多