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。