字符串在python内部是unicode编码,因此在进行编码转换时,要已unicode编码作为中间编码。(注:unicode编码打印出来是中文)
1.编码方法 str.encode()
str.encode()是指定的编码格式编码字符串,str.encode(encoding="utf-8", errors="strict") 有两个可选参数,不填则默认"utf-8"和"strict"
encoding -- 可选参数,要使用的编码方案
errors -- 可选参数,设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值
该方法返回编码后的字符串,它是一个 bytes 对象,这个字节对象是用于下面的解码用的。
2.解码方法 str.decode()
该方法是用来解码编码后的字符串,语法和参数同上。
解码后的字符串即是unicode编码。(注:python乱码转中文就需要解码,用该方法。)
查看编码格式
查看编码格式可以用chardet包
需要pip安装
pip install chardet
使用方法:
chardet.detect(str)
网友评论