速览!快来看看python3和python2的这几个区别

本文对比了Python2和Python3的几个主要区别,包括print从类变为函数、range与xrange的变化、字符串存储方式的差异、异常处理、文件打开方式、标准输入、除法运算以及自定义类型的实现。这些差异对于理解和迁移Python代码至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 print

python2 中 print 为 class

>>> print "This is python2.", 2
This is python2. 2

python3 中 print 为一个函数

>>> print("This is python3.", 3)
This is python3. 3

2 range与xrange

range()在 python2 中会得到一个列表,xrange() 得到的是一个生成器

>>> range(1,5)
[1, 2, 3, 4]
>>> type(range(1,5))
<type 'list'>

>>> xrange(1,5)
xrange(1, 5)
>>> type(xrange(1,5))
<type 'xrange'>

range()在 python3 中会得到一个 range 生成器

>>> range(1,5)
range(1, 5)
>>> type(range(1,5))
<class 'range'>

3 字符串

  • Python2 中存储字符串,使用的 8bit 字符串存储方式,底层使用 ascii 编码的方式,所以字符串有两种不同的格式 str 和 unicode
  • Python3 中存储字符串,是使用的 16bit unicode 字符串变长存储方式

4 异常处理

python2:

>>> try:
...     print "python2"
... except Exception,e:
...     print e
... 
python2

python3:

>>> try:
...     print("python3")
... except Excepttion as e:
...     print(e)
...
python3

5 打开文件

python2 打开方式不止一种:

>>> f = file("test.txt","w")
>>> f.write("python2")
>>> f.close()
>>> f = open("test.txt","w")
>>> f.write("python2")
>>> f.close()

python3使用一种:

>>> f = open("test.txt","w")
>>> f.write("python3")
>>> f.close()

6 标准输入

python2有两种标准输入:

#  输入数据全部转换为字符串
info1 = raw_input("请输入信息:")
请输入信息:12
>>> type(info1)
<type 'str'>

#  输入什么就输出什么数据类型,输入字符串加引号
>>> info2 = input("请输入信息:")
请输入信息:12
>>> type(info2)
<type 'int'>
>>> info2 = input("请输入信息:")
请输入信息:"12"
>>> type(info2)
<type 'str'>

python3一种标准输入,输入数据都返回为字符串:

>>> info3 = input("请输入信息:")
请输入信息:"12"
>>> type(info3)
<class 'str'>
>>> info3 = input("请输入信息:")
请输入信息:12
>>> type(info3)
<class 'str'>

7 除法运算

python2,不使用浮点数,/表示整除,使用浮点数,则使真实除法

>>> 5/2
2
>>> 5.0/2
2.5

python3,/表示除法,//表示整除:

>>> 5/2
2.5
>>> 5//2
2

8 自定义类型

  • python2 中保留了原始的类型继承关系的经典类,同时也支持继承 object 而衍生的新式类,所以在多继承操作过程中会出现两种不同的数据检索方式。
  • python3 中废弃了经典类,只保留了新式类,也就是现在通用的自定义类型,直接 或者间接继承自object。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值