cannot use a string pattern on a bytes-like object(bytes与str互转)
生活随笔
收集整理的這篇文章主要介紹了
cannot use a string pattern on a bytes-like object(bytes与str互转)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python2轉python3遇到的問題
看源碼:
buff = proc.communicate() stritem = buff[0] str_list = re.split(r' +|\n', stritem)運行出現錯誤:
cannot use a string pattern on a bytes-like object
這是因為?stritem = buff[0] 得到的結果為bytes類型,而在python2中為str類型。
這里談到一個轉換問題:bytes與str的互轉
從str到bytes:調用方法encode().
編碼是把Unicode字符串以各種方式編碼成為機器能讀懂的ASCII字符串
從bytes到str:調用方法decode().
將源碼改為:
buff = proc.communicate() stritem = buff[0].decode() str_list = re.split(r' +|\n', stritem)完成
總結
以上是生活随笔為你收集整理的cannot use a string pattern on a bytes-like object(bytes与str互转)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工业控制系统ICS网络安全简析
- 下一篇: Python 16进制与字符串的转换、二