Python2.x和Python3.x的区别

来源:互联网 发布:ubuntu google输入法 编辑:程序博客网 时间:2024/05/27 20:42

python2.x 与python3.x 的区别

所有的区别都来源于python官方文档,建议朝python3.x版本转换的童鞋都看下官方文档https://docs.python.org/3/whatsnew/index.html

主要差别

Old: print "The answer is", 2*2New: print("The answer is", 2*2)Old: print x,           # Trailing comma suppresses newlineNew: print(x, end=" ")  # Appends a space instead of a newlineOld: print              # Prints a newlineNew: print()            # You must call the function!Old: print >>sys.stderr, "fatal error"New: print("fatal error", file=sys.stderr)Old: print (x, y)       # prints repr((x, y))New: print((x, y))      # Not the same as print(x, y)!

python3 不在自动支持空白空格

The print() function doesn’t support the “softspace” feature of the old print statement. For example, in Python 2.x, print "A\n", "B" would write "A\nB\n"; but in Python 3.0, print("A\n", "B") writes "A\n B\n".

排序比较

1.python3不在支持不同类型间的<, <=, >=, >操作,会抛出一个TypeError.None < None也是如此2.sotred和list.sort()不在接受cmp函数,3.删除了cmp函数,删除__cmp__。如果实现排序需要使用__lt__ __hash__ __eq__.如果确实需要使用类似cmp(a,b)的功能。使用如下表达式(a>b)-(a<b)

整型

1.python3不在存在long2.1/2 返回float,如果实现取证使用1//23.长整型repr()不在表现为"11L"4.Octal literals are no longer of the form 0720; use 0o720 instead. 

文本

八进制表示方式。

1.八进制限制使用0o720替代0720

nonlocal关键字

新的解包规则

(a, *b, c) = range(5)  print(a)0print(b)[1, 2, 3]print(c)4

异常新的语法

    try:        pass    except Exception as exe:        pass

元类使用

1.新的语法
        class C(metaclass=M):        pass
2. 模块的__metaclass__语法不在支持
0 0
原创粉丝点击