因为对 Python 3 的推广,预计 Python 2 到 2020 年 4 月 12 日就不再维护了,Python 2 将停止所有的更新,包括安全性更新。
Python 2 和 Python 3 的主要区别:
- 整数相除
- 编码
- 字符串
- xrange
- < >被!=取代
- input 取代 raw_input,取消了2中的input
在Python 2 中,print 是一条语句,语句是一段可执行代码。在Python 3中,print是一个函数,函数接收参数提供返回值,可接收多个参数。如果返回值也是多个,则返回一个元组。
Python 2:
>>>print"hello world"
hello world
>>>print("hello","world")
('hello','world')
Python 3:
>>>print(hello world)
hello world
>>>print("hello","world")
hello world
- 整数相除
Python 2 中,整数相除默认是整型。Python 3 中,整数相除默认为浮点型
Python 2:
>>>print("1/2",1/2)
('1/2', 0)
Python 3:
>>>print("1/2",1/2)
1/2 0.5
- 编码
Python 2 中,默认编码是 asscii,asscii编码是应用于拉丁字母的编码系统,程序内用中文常导致出现编码问题。在Python 3 中采用了 UTF-8 作为默认编码,UTF-8属于unicode编码,支持大多数语言,且可变长度,空间较为节省。在Python 3 中写代码再不用声明# coding:utf-8
- 字符串
Python2 中字符的类型:
str: 已经编码后的字节序列
unicode: 编码前的文本字符
Python3 中字符的类型:
str: 编码过的 unicode 文本字符
bytes: 编码前的字节序列
二进制字节 | unicode字符 | |
---|---|---|
python2 | str类型 | unicode类型 |
python3 | bytes类型 | str类型 |
为了避免出错,在python 2 中应在文本字符串前面加上u.
- xrange
Python 2 中range 返回一个列表,xrange返回一个迭代器。
Python 3中没有xrange。 range 方法就相当于 Python 2中的 xrange 方法
同时像map函数等,python3 比返回列表的函数改为了返回迭代器
input
在Python 2 中输入有 input 和 raw_input 两个函数,而Python 3中的 input 等同Python 2 中的 raw_input ,默认接收的数据是str类型。
Python 2:
# coding:utf-8
i = input("输入时带引号:")
b = input("输入时不带引号:")
print "i:", type(i)
print "b:", type(b)
输入时带引号:"233"
输入时不带引号:233
i: <type 'str'>
b: <type 'int'>