Python 2.x 和 Python3.x 的区别
前言
future 模块
Python 3 介绍的 一些 Python 2 不兼容的关键字和特性可以通过在 Python 2 的内置 __future__
模块导入。如果你计划让你的代码支持 Python 3,建议你使用 __future__
模块导入。例如,如果我想要 在Python 2 中表现 Python 3 中的整除,我们可以通过如下导入。
from __future__ import division
官方参考文档
编码
源码文件编码
在 python 2.x 版本,python 源码文件默认使用 Ascii
编码,所以无法直接显示中文。需要在源码文件头部通过声明 # -*- encoding: utf-8 -*-
来告诉解释器使用 utf-8
编码处理源文件。
而 python 3.x 源码文件默认以 UTF-8
编码方式处理。
字符串编码
早期 Unicode 标准并未发布时,python 的字符串str
默认使用ASCII
进行编码。后来python2.0
提供了一种新的存储文本数据的数据类型:Unicode
对象,添加了对 Unicode 的支持。它可以用来存储和操作 Unicode
数据。所以 python 2 同时有Ascii
编码的str
和Unicode
字符串。
到了 python 3 以后,python
删除了Unicode
对象类型,使字符串均由Unicode
编码。
标准输入输出
输出
删除了 python 2 的print
语句 ,取而代之的是 print()
函数。 Python 2.6 与 Python 2.7 部分地支持这种形式的 print
语法。在 Python 2.6 与Python 2.7 里面,以下三种形式是等价的:
print "fish"
print ("fish") # 注意print后面有个空格
print("fish") # print()不能带有任何其它参数
如果 Python 2.x 版本想使用使用 Python 3.x 的 print 函数,可以导入 __future__
包,该包禁用 Python2.x 的 print
语句,采用 Python 3.x 的 print
函数
from __future__ import print_function
print