Python编码(1)

2.7:
1.Unicode统一了语言,常用两个字节表示一个字符

eg:读取记事本中的内容时 计算机先将utf-8字符转换为Unicode到内存中,保存时再将Unicode转换为utf-8保存到文件。
eg2:浏览网页时,服务器将Unicode转换为utf-8再传输到浏览器

2.Unicode编码成utf-8,一个中文Unicode字符变为三个utf-8字符,一个中文Unicode字符变为两个gbk字符
>>> u'ABC'.encode('utf-8')

'ABC'
>>> u'中文'.encode('utf-8')
'xe4xb8xadxe6x96x87'

>>> len(u'ABC')
3
>>> len('ABC')
3
>>> len(u'中文')
2
>>> len('xe4xb8xadxe6x96x87')
6

>>> u'中文'.encode('gb2312')
'xd6xd0xcexc4'

反过来,把UTF-8编码表示的字符串'xxx'转换为Unicode字符串u'xxx'用decode('utf-8')方法:

>>> 'abc'.decode('utf-8')
u'abc'
>>> 'xe4xb8xadxe6x96x87'.decode('utf-8')
u'u4e2du6587'
>>> print 'xe4xb8xadxe6x96x87'.decode('utf-8')
中文

3.Python 3版本中,字符串是以Unicode编码的
2版本示例:
>>> ord('') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> ord('') TypeError: ord() expected a character, but string of length 2 found
3版本示例:
>>> ord('') 20013 Python3以Unicode表示的str通过encode()方法可以编码为指定的bytes,例如: >>> 'ABC'.encode('ascii') b'ABC' >>> '中文'.encode('utf-8') b'xe4xb8xadxe6x96x87' 不用在中文前加u了

Windows下Python2.7版本解释器默认是gbk编码的

>>> len(u'中国')
2
>>> len('中国')
4
>>> unicode('中国','utf8')

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    unicode('中国','utf8')
  File "C:Python27libencodingsutf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
>>> unicode('中国','gbk')
u'u4e2du56fd'
原文地址:https://www.cnblogs.com/qqzj/p/7381007.html