经常被encode、decode搞得晕晕的,特别是玩爬虫的时候,每次都想敷衍了事,最终还是躲不过,还是要耐下心来好好的分析分析
首先,python3两种表示字符序列的类型:bytes 和 str,bytes的实例是包含原始的8位值,str则是包含Unicode字符的,而在python2中
同样也有两种表示字符序列的类型:str 和 unicode, str的实例包含原始的8位值,unicode包含Unicode字符。这8位值就是原始的字节,由
于每个字节有8个二进制,故而是原始的8位值,也叫原生8位值或纯8位值。用Unicode字符来表示二进制数据的方法比较多,常见的就是
UTF-8了, 但是python3的str、python2的unicode都没有与特定的二进制编码形式相关联,所以要把Unicode字符转换成二进制就需要使用
encode编码了,二进制变成Unicode需要decode解码来帮忙了。
由于工作中经常会用到两者直接的转换,可以写两个帮助函数方便以后随用随取:
python3中bytes/str总是返回str的方法:
1 defto_str(bytes_or_str):2 ifisinstance(bytes_or_str, bytes):3 value = bytes_or_str.decode('utf-8')4 else:5 value =bytes_or_str6 return value
python3中bytes/str总是返回bytes的方法:
1 defto_bytes(bytes_or_str):2 ifisinstance(bytes_or_str, str):3 value = bytes_or_str.encode('utf-8')4 else:5 value =bytes_or_str6 return value
python2中str/unicode总是返回unicode的方法:
1 defto_unicode(unicode_or_str):2 ifisinstance(unicode_or_str, str):3 value = unicode_or_str.decode('utf-8')4 else:5 value =unicode_or_str6 return value
python2中str/unicode总是返回str的方法:
1 1 defto_str(unicode_or_str):2 2 ifisinstance(unicode_or_str, unicode):3 3 value = unicode_or_str.encode('utf-8')4 4 else:5 5 value =unicode_or_str6 6 return value