Python2和Python3的字符串编码和类型

一、字符串编码和类型

任何编码格式的字符串,都可以和Unicode互相转换。


gbk -> utf8

# 将字符串按指定格式进行解码,返回Unicode字符串
unicode_str = gbk_str.decode("gbk")

# Unicode字符串按指定格式进行编码,返回对应编码字符串
utf8_str = unicode_str.encode("utf-8")


爬虫获取网页字符串的编码格式,取决于网页的charset=gbk


Python2: 编码和类型
str 类型:非Unicode编码字符串
unicode 类型:Unicode编码字符串


Python3: 编码和类型
str 类型:Unicode编码字符串
bytes 类型:非Unicode编码字符串和二进制数据,前面有个'b'


# 将字符串按指定格式进行解码,返回Unicode字符串
unicode_str = gbk_str.decode("gbk")

# Unicode字符串按指定格式进行编码,返回对应编码字符串
utf8_str = unicode_str.encode("utf-8")

二、解释器编码(Linux) :默认编码转换,用于文件写入

>>> import sys
>>> sys.getdefaultencoding()


Python2 :ascii 只能帮忙转换字母、数字
Python3 :utf-8 默认转为utf-8

字符串 utf-8 存为 utf-8文件 (OK)
字符串 unicode,转为utf-8, 存为 utf-8文件 (OK)

字符串 unicode,如果不转码,解释器会尝试转为utf-8,存为utf-8文件 (OK)


当字符串是包含中文的Unicode时,Python2不能直接写入文件,会报错

如果遇到字符串和需要保存的文件不一致:
1. 自己手动转为匹配的编码格式
2. 让解释器帮忙转换,Python2有可能做导致 UnicodeEncodeError


在程序员没有转换编码的前提下:
Python3的解释器:可以将Unicode 转为utf-8 写入Linux文件下(解释器编码UTF-8)
Python2的解释器:不能将 Unicode 写入到Linux文件下(解释器编码ASCII)


Python2下处理编码的万能钥匙:

将Python2的解释器编码ascii 改为 utf-8 (解释器环境等于Python3)
>>> import sys
>>> reload(sys)
>>> sys.setdefaultencoding("utf-8")


三、终端编码(Linux)
Python2 : utf-8

Python3 : Unicode


四、保存的文件编码
只和操作系统有关,Linux是utf-8 Windows GBK

Python3:

with open("xxx.txt", "w", encoding="utf-8") as f:
f.write(xxxx)


Python2 ;没有encoding参数


>>> with open("xxx.txt", "w") as f:
... f.write("你好".decode("utf-8"))
...

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
UnicodeEncodeError: 'ascii' codec cant encode characters in position 0-1: ordinal not in range(128)


>>> with codecs.open("xxx.txt", "w", encoding="utf-8") as f:
... f.write("你好".decode("utf-8"))
...

五、代码文件的编码格式
Python2: ascii #coding:utf-8
Python3: utf-8

Google :PageRank(根据网页流量排名)
Baidu :超链分析(Robin Li),竞价排名(给钱多排名靠前)


不要看一下午视频,只看不清楚的地方(11:55)
“我亦无他,唯手熟尔。”
照着抄代码 - 默写代码 - 改写代码 - 自己写出自己的代码

Python自带模块:
/usr/lib/python2.7

Python第三方模块(pip install xxx)
/usr/local/lib/python2.7/site-packages/

猜你喜欢

转载自www.cnblogs.com/snailon/p/9034369.html