Python2 和 Python3 的主要区别——内含思维导图

     因为对 Python 3 的推广,预计 Python 2 到 2020 年 4 月 12 日就不再维护了,Python 2 将停止所有的更新,包括安全性更新

     Python 2 和 Python 3 的主要区别:

 

  • print
  • 整数相除
  • 编码
  • 字符串
  • xrange
  • < >被!=取代
  • input 取代 raw_input,取消了2中的input

 

 

  • print

      在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字符
python2str类型unicode类型
python3bytes类型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'>

  • 5
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值