Python 2.x和Python 3.x版本之间有什么区别?
在本文中,我们将使用示例来查看Python 2.x和Python 3.x之间的一些重要区别。
- print函数
- 整数除法
- Unicode字符串
- 抛出异常
__future__- xrange
下面是Python 2.x和Python 3.x之间的主要区别
更多Python相关文章,请阅读:Python 教程
print函数
在Python 2.x中,print关键字被Python 3.x中的print()函数替换。因为解释器将其解析为表达式,所以如果在print关键字后提供空格,则Python 2中的括号有效。
示例
这是一个示例,以了解print函数的用法。
print 'Python'
print 'Hello, World!'
print('Tutorialspoint')
输出
当以上代码在这两个版本上编译时,显示输出如下
Python 2.x版本
Python
Hello, World!
Tutorialspoint
Python 3.x版本
File "main.py", line 1
print 'Python'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean
print('Python')?
以下代码行可用于在Python中打印语句。
print('Tutorialspoint')
输出
在每个版本中获得的输出如下所示。
Python 2.x版本
Tutorialspoint
Python 3.x版本
Tutorialspoint
整数除法
Python 2将没有小数点的数字解释为整数,这可能会导致一些意外的除法结果。如果在Python 2代码中键入5/2,则计算的结果将是2,而不是您可能期望的2.5。
示例
下面的示例描述了Python中整数除法的工作方式。
print ('5 / 2 =', 5 / 2)
print ('5 // 2 =', 5 // 2)
print ('5 / 2.0 =', 5 / 2.0)
print ('5 // 2.0 =', 5 // 2.0)
输出
两个版本的输出结果如下。
在Python 2.x版本中
5 / 2 = 2.5
5 // 2 = 2
5 / 2.0 = 2.5
5 // 2.0 = 2.0
在Python 3.x版本中
5 / 2 = 2.5
5 // 2 = 2 5
/ 2.0 = 2.5 5
// 2.0 = 2.0
Unicode字符串
在Python 2中,隐式的str类型是ASCII。然而,Python 3.x中的隐式str类型是Unicode。
- 在Python 2中,如果想将字符串存储为Unicode,则必须用“u”标记字符串。
-
在Python 3中,如果想将字符串存储为字节码,则必须使用“b”标记字符串。
示例1
下面看一个例子,比较Python 2和Python 3中Unicode的区别。
print(type('default string '))
print(type(b'string which is sent with b'))
输出
每个不同版本的输出如下。
在Python 2版本中
<type 'str'>
<type 'str'>
在Python 3版本中
<class 'str'>
<class 'bytes'>
例2
Python 2和3不同版本中Unicode的另一个示例如下。
print(type('default string '))
print(type(u'string which is sent with u'))
输出
得到的输出如下。
在Python 2版本中
<type 'str'>
<type 'unicode'>
在Python 3版本中
<class 'str'>
<class 'str'>
抛出异常
在Python 3中引发异常需要修改语法。如果您希望向用户显示错误消息,则必须使用该语法。
raise IOError(“your error message”)
上述语法适用于Python 2和Python 3。
但是,以下代码仅适用于Python 2,不适用于Python 3。
raise IOError, “your error message”
__future__模块
这不是两个版本之间的区别,但非常重要。__future__模块是为了帮助迁移到Python 3.x而创建的。
如果想要在Python 2.x代码中使用Python 3.x兼容性,则可以在我们的代码中使用future导入。
示例
以下代码可用于导入和使用print_function。
from __future__ import print_function
print('Tutroialspoint')
输出
所得到的输出如下。
Tutorialspoint
极客教程