Python 字符编码
环境
python 2.7:因为python3默认的字符串为unicode编码,所以主要还是要注意python2中的编码问题
编解码
首先,文件头加下面的代码,使默认的字符串为 utf-8
编码,以方便处理
# -*- coding:utf-8 -*-
然后,python提供encode 和 decode 方法作为字符串的编解码工具,使用方法如下:
# utf-8 解码
s1 = "这里是一个utf8编码的字符串"
s2 = s1.decode("utf-8") # s2 为 unicode
# unicode 编码
s3 = s2.encode("utf-8") # s3 为utf8编码
# 取出unicode中的编码位
s4 = s2.encode("unicode-escape") # s4 为 utf8 编码的
print(s4) # \u8fd9\u91cc...