龙空技术网

Python2与Python3的区别

扣丁学堂 92

前言:

眼前小伙伴们对“简述python2与python3中的区别”大约比较关怀,看官们都想要了解一些“简述python2与python3中的区别”的相关文章。那么小编也在网络上搜集了一些有关“简述python2与python3中的区别””的相关知识,希望同学们能喜欢,我们一起来了解一下吧!

区别1.print的使用

print在python2当中是一个类,通过声明字符串来工作。python3中则是一个函数,字符串作为参数。

	python2:	print 'Hello, World!'	python3:	print('Hello, World!')
区别2.input的使用

python2通过input函数读取到的数据返回值是int;通过raw_input函数读取到的数据返回值str。python3通过input函数读取到的数据返回值是str。

区别3.整除

python2中/表示根据除数被除数小数点位得到结果,//表示进行除运算后得到的整数部分。python3中/表示计算除运算后得到浮点数,%表示取余,/表示进行除运算后得到的整数部分

python2:

	print '3 / 2 =', 3 / 2	print '3 // 2 =', 3 // 2	print '3 / 2.0 =', 3 / 2.0	print '3 // 2.0 =', 3 // 2.0

结果

3 / 2 = 13 // 2 = 13 / 2.0 = 1.53 // 2.0 = 1.0

python3:

	print('3 / 2 =', 3 / 2)	print('3 // 2 =', 3 // 2)	print('3 / 2.0 =', 3 / 2.0)	print('3 // 2.0 =', 3 // 2.0)

结果

3 / 2 = 1.53 // 2 = 13 / 2.0 = 1.53 // 2.0 = 1.0
区别4. range 与 xrange

python2 range(0, 4) 结果是列表 [0,1,2,3 ]

python3 list(range(0, 4)) 结果是列表 [0,1,2,3 ]

python2 xrange(0, 4) 适用于for循环的变量控制

python3 range(0, 4) 适用于for循环的变量控制

区别5. 字符串的编码

python2 字符串以 8-bit 字符串存储

python3 字符串以 16-bit Unicode 字符串存储

区别6. try except 语句的变化

python2

 try: 	pass except Exception, e:    pass

python3

try:	passexcept Exception as e :    pass
区别7. 打开文件的方式

python2

file(…)open(…)

两种方式打开

python3

open(…)

一种方法

区别8. chr与ord的变化

python 2

chr(K) 将编码K 转为字符,K的范围是 0 ~ 255

ord© 取单个字符的编码, 返回值的范围: 0 ~ 255

python 3

chr(K) 将编码K 转为字符,K的范围是 0 ~ 65535

ord© 取单个字符的编码, 返回值的范围: 0 ~ 65535

区别9. 字节数组对象

(一) 初始化

 a = bytearray(10) # a 是一个由十个字节组成的数组,其每个元素是一个字节,类型借用 int # 此时,每个元素初始值为 0
a = bytearray(10)a[0] = 25# 可以用赋值语句更改其元素,但所赋的值必须在 0 ~ 255 之间

(三) 字节数组的切片仍是字节数组

(四) 字符串转化为字节数组

#coding=gbks ="你好"b = s.encode("gbk")     	# 先将字符串按某种“GBK”编码方式转化为 bytesc = bytearray(b)          	#再将 bytes 转化为 字节数组

也可以写作

c = bytearray("你好", "gbk")

(五) 字节数组转化为字符串

c = bytearray(4)c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68s = c.decode("gbk")print (s)# 应显示: ABCD

(六) 字节数组可用于写入文本文件

#coding=gbkf = open("c:\\1234.txt", "wb")s = "张三李四abcd1234"# 在 python2.4 中我们可以这样写:# f.write(s)# 但在 python 3.0中会引发异常b = s.encode("gbk")f.write(b)c=bytearray( "王五","gbk")f.write(c)f.close()input("?")

标签: #简述python2与python3中的区别