当前位置:   article > 正文

python3与python2的区别

python3与

1.字符编码&字符串类型

python2:默认为Ascii码。其string类型包括了str和unicode。
unicode类型表示字符串序列
str类型表示字节序列
对于中文需要使用utf-8:

#--coding: utf-8-- #encoding=utf-8
  • 1

python3:默认为utf-8编码,所有编写的代码都是unicode,python解析器在运行的时候,内部都转换(除非你显示定义为bytes类型)为unicode
str类型表示字符串序列
byte类型表示字节序列

2.包的导入方式

python2:相对路径导入
python3:绝对路径导入

3.缩进

python2:支持space和tab混用,一个tab等于8个space
python3:不支持混用

4.新式类与旧式类

旧式类与新式类的区别:

python2:存在老式类与新式类的区别
python3:全部使用新式类

5.bool类型 与int 类型
bool:
python2:True 和False是变量,可以赋值
python3:True和False是关键字,不可变

int:
python2:存在int 和long
在这里插入图片描述

python3:只有int
在这里插入图片描述

6.运算符‘/’和‘//’

python2:
‘/’ :若为两个整形数进行运算,结果为整形,但若两个数中有一个为浮点数,则结果为浮点数;

3/2 =1  3.0/2 = 1.5
  • 1

python3:
‘/’ :真除法 返回实际结果
‘//’ :向下取整除法

7.异常处理机制

Python2
抛出异常:raise IOError, "error“
捕捉异常:

try
	#
except Errorname,err:
	#
  • 1
  • 2
  • 3
  • 4

Python3
抛出异常:raise IOError("file error")
捕捉异常:

try
	#
except Errorname as err:
	#
  • 1
  • 2
  • 3
  • 4

8.变量泄露(作者只知道在进行列表推导时会出现这种情况):

i=6
print((i for i in range(4)))#列表推导
print(i)

#python2  输出:[0,1,2,3] 3
#python3  输出:[0,1,2,3] 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

python2:列表推导会修改外部相同名称变量的值
python3:不会

9.输入

python 2: input 默认接收整形数据,str类型要用引号包起来,或用raw_input函数可以接收字符串

python 3: input 函数接收,获得输入类型为字符型

10.部分语句或函数废弃

  • print 语句被 Python3 废弃,统一使用 print 函数
print 'hello world'  #python2
print('hello world') #python2 & 3 
  • 1
  • 2
  • exec 语句被 python3 废弃,统一使用 exec 函数
  • execfile 语句被 Python3 废弃,推荐使用exec(open("./filename").read())
  • 不相等操作符"<>“被 Python3 废弃,统一使用”!="
print(3<>4) #True python2
print(3!=4)#true python2 & 3
  • 1
  • 2
  • long 整数类型被 Python3 废弃,统一使用 int
  • xrange 函数被 Python3 废弃,统一使用 range,Python3 中 range 的机制也进行修改并提高了大数据集生成效率
#range和xrange用法相同,不同的是xrange不是生成一个序列,而是作为一个生成器,即生成一个取出一个
  • 1
  • Python3 中这些方法再不再返回 list 对象:dictionary 关联的
    keys()、values()、items(),zip(),map(),filter(),但是可以通过 list 强行转换:

  • 迭代器 iterator 的 next()函数被 Python3 废弃,统一使用 next(iterator)

  • raw_input 函数被 Python3 废弃,统一使用 input 函数

  • 字典变量的 has_key 函数被 Python 废弃,统一使用 in 关键词

  • file 函数被 Python3 废弃,统一使用 open 来处理文件,可以通过 io.IOBase 检查文件类型

  • apply 函数被 Python3 废弃

  • 异常 StandardError 被 Python3 废弃,统一使用 Exception。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/44976
推荐阅读
相关标签
  

闽ICP备14008679号