Python 2 和 3 的区别记录

Python 2 和 3 的区别记录

print

python2:关键字,可以 print a,也可以 print(a)

python3:内置函数,必须带(),print(a)

reload()

python2:内置函数,可以直接使用

python3:这样才可以使用:

if sys.version_info.major > 2:
    from importlib import reload

super

exec

python2.6+:

try:

except Exception as e:

sorted() 内置函数

python2:sorted(iterable, cmp = None, key = None, reverse = False)

python3:sorted(iterable, key = None, reverse = False)

例子:

lst = [[2,6],[5,3]]

lst_sorted = sorted(lst, key = lamba x: x[1])

xrang() 和 range()

python2:range() 返回 list,xrange() 返回 iterator

python3:移除 xrange(),range() 返回 iterator

*args 和 keyword = 参数的顺序

python2:只能 def fun(*args, **kwargs): a = kwargs.pop('a', defaultValue),python3 的方式目前没有在 __feature__ 中

python3:def fun(*args, a = 1)

unicode()

python 3 中字符串默认是utf8,这个方法已经去掉了,如果在python 2中 调用 s = unicode(s, 'utf-8'),那么在python 3中不用转

 Dict 字典 has_key() 和 in Dict

python3 中已经移除该方法属性,在 python3 和 python2 中都可以使用 [key] in [Dict] 来判断是否有key

d = {'a':1,"b":2}

print('a' in d)

print('c' not in d)

 

https://wiki.python.org/moin/PortingPythonToPy3k

原文地址:https://www.cnblogs.com/ibingshan/p/9798894.html