字符编码转换

Python字符编码转换:

一、Python3中的编码转换(python3中默认就是unicode编码)

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#author huan

tim = ''
#转为UTF-8编码
print(tim.encode('UTF-8'))
#转为GBK编码
print(tim.encode('GBK'))
#转为ASCII编码(报错为什么?因为ASCII码表中没有‘天’这个字符集~~)
print(tim.encode('ASCII'))

二、Python2.x中的编码转换

因为在python2.X中默认是ASCII编码,你在文件中指定编码为UTF-8,但是UTF-8如果你想转GBK的话是不能直接转的,需要Unicode做一个转接站点。

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#author huan

import chardet
tim = '你好'
print chardet.detect(tim)
#先解码为Unicode编码,然后在从Unicode编码为GBK
new_tim = tim.decode('UTF-8').encode('GBK')
print chardet.detect(new_tim)

#结果
'''
{'confidence': 0.75249999999999995, 'encoding': 'utf-8'}
{'confidence': 0.35982121203616341, 'encoding': 'TIS-620'}
'''
原文地址:https://www.cnblogs.com/happystudyhuan/p/12310455.html