Python3编码与转码

python3中有2种编码格式,分别为str与byte,这里的str相当于Python2中的unicode,byte相当于Python2中的str。再者python3将python源代码编码从ascii改成了utf-8,从外部接收的编码自动转化成了str(Python2中的unicode),大大减少产生编码异常的点。与Python2一样,3中的编码原则就是将外部接收的字符编码成str(unicode字符),输出时再编码成bytes编码
1.Python3的bytes与str
  bytes表示字符的原始8位值,str表示Unicode字符。将unicode字符表示为二进制数据(原始8位值),最常见的编码方式就是UTF-8。python2与3中的unicode字符没有和特定的二进制编码相关联,因此需要使用encode方法。
  在python3中bytes与str是绝对不会等价的,即使字符内容为””,因此在传入字符序列时必须注意其类型。
  Python3已经把源代码编码以及系统编码从ascii都变成了utf-8,避免了中文报错。
  import sys
print(sys.getdefaultencoding())
输出结果:utf-8
#字符串编码
str1 = '你好'
print(type(str1))
<class 'str'>
str2 = str1.encode('utf-8')
print(type(str2))
<class 'bytes'>
#网页编码
import urllib.request
f = urllib.request.urlopen('http://www.cnblogs.com/coffy/p/5748292.html').readlines()
print(type(f[10]))
print(f[10].decode('utf-8'))
输出结果:
<class 'bytes'>
<link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/coffy/rss"/>
#返回的是bytes格式的,只要decode转化为str就ok了。
#文件编码
f = open('1.txt').read()
print(type(f))
print(f)
print(type(f).encode('utf-8'))
print(f.encode('utf-8'))
输出结果:
<class 'str'>
3222
b'utf-8'
b'3222'
#从文件中读取出来的是str(2.x中的unicode),因此不用转码。

posted @ 2017-06-22 14:48  孤鸟的悲歌丶  阅读(2616)  评论(0编辑  收藏  举报