Python3与Python2的差别


基于python3浅谈python3与python2的差别。因为现今主流Python3,可是以前用Python2作的项目,还得维护,因此做为python工做者,难免要了解其中差别,其中,Python2 有 ASCII str() 类型,unicode() 是单独的,不是 byte 类型。而 Python3.X 源码文件默认使用utf-8编码,以及一个字节类:byte 和 bytearrays。这就使得如下代码是合法的: python

编码差别: markdown

我 = 'zhongguo' 函数

print(我)ui

Python3结果:zhongguo编码

:python2中是不合法的,不管是代码仍是注释都是不能出现汉字的,除非申明:#!/usr/bin/python -*- coding: UTF-8 -*-spa

做为一种默认规范或者代码素养,一般不用汉字,尽可能让代码写的python点! .net


python3与python2最大的区别就是print输出请参考print的使用:https://blog.csdn.net/u010986753code

Python 3版本中print语句没有了,取而代之的是print()函数。orm

print差别:对象

正确输出"life is short we neeed python!"代码以下:

print('life is short we neeed python!')

Python3结果:life is short we neeed python!

Python2中的打印:

print "life is short we neeed python!"/

print 'life is short we neeed python!'/

print ('life is short we neeed python!')

输出结果都是同样的!

整除差别

> print(7/3)>

Python3结果:2.3333333333333335

> Python2结果:2

> Python3表示整除是print(7//3)

不等号的差别:

Python2中不等于有两种写法 != 和 <>

Python3中去掉了<>, 只有!=一种写法

整型的差别:

Python2中有一种整型—int和长整型-long

Python3中只有一种整型—int

提示信息的差别:

Python2中raw_input( "提示信息" )和input( "提示信息" )

Python3中只有input( "提示信息" )

打开文件的差别:

Python2中file( ..... )或 open(.....)

Python3中只有open(.....)

map、filter 和 reduce的差别:

Python2在交互模式下:

>>> map

<built-in function map>

>>> filter<built-in function filter>

>>> reduce<built-in function reduce>

它们输出的结果类型都是列表:

>>> map(lambda x:x +2, [4,1,3])

[6, 3, 5]

>>> filter(lambda x:x %2 ==0,range(9))

[0, 2, 4, 6, 8]

Python3在交互模式下:它们从函数变成了类,其次,它们的返回结果也从当初的列表成了一个可迭代的对象

>>> map<class 'map'>

>>> map(print,[1,2,3])

<map object at 0x10d8bd400>

>>> filter<class 'filter'>

>>> filter(lambda x:x % 2 == 0, range(10))

<filter object at 0x10d8bd3c8>

遍历元组

对于比较高端的 reduce 函数,它在 Python3中已经不属于 built-in 了,被挪到 functools 模块当中。若是须要编写一个遍历元组的列表解析,Python2不须要在元组值周围加上括号。在python3里,这些括号是必需的。

Python2中[ i for i in 1, 2]

Python3中[i for i in (1,2)]

得到必定范围内的数字

python2里,有两种方法得到必定范围内的数字:range(),返回一个列表,还有xrange(),返回一个迭代器。

python3 里,range()返回迭代器,xrange()再也不存在。

Python2中[ i for i in 1, 2]

Python3中[i for i in (1,2)]

欢迎关注小婷儿的博客 https://blog.csdn.net/u010986753不足之处请留言,会尽快修改!