乱码
Python2的 默认编码是ASCII,不能识别中文字符,需要显式指定字符编码;
Python3的 默认编码 为Unicode,可以识别中文字符。
编码探测
可用以下两种方法进行探测
# coding=utf-8
s_str = "天天向上"
s_uni = u"天天向上"
#法一
if isinstance(s_str, str):
print type(s_str).__name__
if isinstance(s_uni, unicode):
print type(s_uni).__name__
#法二
import chardet
print chardet.detect(s_str)
print chardet.detect(s_uni) #这是错误的,参数只能为str类型; chardet.detect(s_uni.encode('utf-8'))
转换
UNICDOE才是真正的字符串,而用ASCII、UTF-8、GBK等字符编码表示的是字节串。
字符编码的作用就是将人类可识别的字符转换为机器可识别的字节码,以及反向过程。
python2
python2.x字符串格式有
- str
默认格式(字符编码为ASCII)
- unicode
字节串–>decode(‘原来的字符编码’)–>Unicode字符串–>encode(‘新的字符编码’)–>字节串
#!/usr/bin/env python
# -*- coding:utf-8 -*-
utf_8_a = '我爱中国'
gbk_a = utf_8_a.decode('utf-8').encode('gbk')
print(gbk_a.decode('gbk'))
python3
Python3中定义的字符串默认就是unicode,因此不需要先解码,可以直接编码成新的字符编码:
字符串–>encode(‘新的字符编码’)–>字节串
#!/usr/bin/env python
# -*- coding:utf-8 -*-
utf_8_a = '我爱中国'
gbk_a = utf_8_a.encode('gbk')
print(gbk_a.decode('gbk'))