Python 2 to 3
这篇博客主要讲讲Python2与Python3的少部分异同
-
print
首先最简单的区别的必然是print语句,简单来说就是有无括号
-
unicode字符串
-
Python2中必须使用 u'unicode_str'来表示这是unicode字符串
-
Python3默认是unicode,所以可以直接时候输入'unicode_str'
-
-
<>
-
Python3不支持<>这个运算符,需使用!=
-
Python2则两者都支持
-
-
字典部分区别
-
has_key()
-
Python2使用dict.has_key("xx"),来检测字典中是否包含xx
-
Python3不支持此方法,使用 "xx" in dict 即可
-
-
keys()、items()
-
Python2使用此方法默认返回值为列表
-
Python3必须使用list方法进行转换
-
-
-
调用部分模块的区别
-
urllib、urllib2
-
Python2 直接调用两者即可
-
Python3 合并了urllib2,综合到了urllib中
-
-
commands --> subprocess
-
-
filter()
-
Python2 采用了filter(xxx) 返回列表
-
Python3 要使用list方法,才能使filter返回列表
-
-
map()
-
Python2 返回列表
-
Python3 返回迭代器
-
-
reduce()
-
Python2 直接使用
-
Python3 需要引入from functools import reduce
-
-
try...except
-
Python2 使用except someError, e
-
Python3 使用except someError as e:
-
-
raise
-
Python2 使用raise xxx, 'some msg'
-
Python3 使用raise xxx('some msg')
-
-
xrange()
-
Python2 使用xrange(10)
-
Python3 使用range(10)
-
-
raw_input()
-
Python2 使用raw_input()
-
Python3 使用input(),Python2的input()转为eval(input())
-
-
lambda()
-
Python2 使用lambda (x, (y, z)): x + y + z
-
Python3 使用lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]
-
-
zip()
-
Python2 使用zip(a, b, c)即可返回一个元组组成的列表
-
Python3 要使用list(zip(a, b, c))才能返回列表,否则返回迭代器
-
-
对元组列表解析
-
Python2 [i for i in 1, 2]
-
Python3 [i for i in (1, 2)]
-