1. 程式人生 > >一勞永逸解決:TypeError: cannot use a string pattern on a bytes-like object

一勞永逸解決:TypeError: cannot use a string pattern on a bytes-like object

TypeError: cannot use a string pattern on a bytes-like object

最近寫程式碼,python2和python3之間切換,難免會碰到一些問題,有些方法比如re模組的findall要求傳入的是字串格式的引數,urllib.request.urlopen(url).read()返回的是bytes型別(這個是python3中才有的型別,所以很多python2中的方法都相應更改了)的,這樣傳參就會報以上錯誤。

python3中Unicode字串是預設格式(就是str型別),ASCII編碼的字串(就是bytes型別,bytes型別是包含位元組值,其實不算是字串,python3還有bytearray位元組陣列型別)要在前面加操作符b或B;python2中則是相反的,ASCII編碼字串是預設,Unicode字串要在前面加操作符u或U

一勞永逸的解決方法就是根據你傳進來的引數自動辨別編碼格式,然後進行相應的解碼,就搞定啦:

import chardet   #需要匯入這個模組,檢測編碼格式
encode_type = chardet.detect(html)  
html = html.decode(encode_type['encoding']) #進行相應解碼,賦給原識別符號(變數)
從str到bytes:呼叫方法encode().
編碼是把Unicode字串以各種方式編碼成為機器能讀懂的ASCII字串
從bytes到str:呼叫方法decode().