decode 与 encode详解
decode(解码)作用:将其他编码
的字符串转换成unicode
编码
例:str1.decode(‘gb2312’)
,表示将gb2312编码的字符串str1转换成unicode编码。
encode(编码)作用:将unicode
编码转换成其他编码
的字符串
例:str2.encode(‘utf-8’)
,表示将unicode编码的字符串str2转换成utf-8编码。
注意:decode和encode不加参数的时候默认参数为’utf-8
在做编码转换时,通常需要以unicode作为中间编码
,即先将其他编码的字符串解码(decode)成unicode,
再从unicode编码(encode)成另一种编码。
爬虫中的编码注意事项
有的时候需要用到请求对象的限制,即:
urlib.request.Request(url=url,data=data,headers=headers)
其中的data参数一般是字典,那么需要进行转换:
1 | python复制代码 import urllib.request |
文件问题
1.在文件中直接写入str类型的字符,会导致乱码
1 | ini复制代码string = '你好!我是中文' |
����������
2.为了解决乱码,将str类型转换为bytes类型,在写入
1 | python复制代码 string = '你好!我是中文' |
你好!我是中文
3.解决乱码的另一种形式
1 | python复制代码 string = '你好!我是中文' |
你好!我是中文
本文转载自: 掘金