从英文意思上看,encode和decode分别指编码和解码。在python中,Unicode类型是作为编码的基础类型。
1 | encode decode |
encode的作用是将其他编码的字符串转换成unicode编码,如str1.encode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。
decode的作用是将unicode编码转换成其他编码的字符串,如str2.decode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码
因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码
下面咱们用几个例子来看下:
1 | s = '中国,你好' |
运行结果是:
1 | type is <class 'str'> |
看完运行结果大家就知道怎么用了。😆
原文链接: http://yoursite.com/2019/02/26/python-encode和decode函数的用法/
版权声明: 转载请注明出处.