[dev][python] 从python2进阶到python3你都需要了解什么

基于python2快速掌握python3

0. 前言

  1. 这是一篇road map。
  2. 如果你会python2,读完这篇文章之后,你将掌握python3

1. 为什么会出现python3

Why Python3 exists

  1. python2中的string类型存在歧义,它是一个C字符串也是一个str对象。
    python3去除这一不明确的string用法。
  2. python2 对unicode兼容不好。
    因为python的第一个版本早于unicode的第一个版本。
  3. python的后续版本不希望向后兼容1)和2)

基于以上三点,出现了python3. 总之就是想弄的更好又不想束手束脚。

2. python的禅

Zen of python

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

3. 基于python2的python3教程

Porting to Python3

3.1 不得不porting的两个理由

1. Python 3 is simply a nicer language than Python 2.
2. more code will be written in Python 3 than in Python 2 over the history of the Python language, so not porting means your project will eventually be left behind.

3.2 主要的区别

3.2.1 除法

python2里的除法是与C语言保持一致的,一个斜杠“/”代表向下取整。
python3里不在是这样,有两个符号表示除法“/”,和“//”
一个斜线‘/’代表严格意义的除法,结果是float类型。结果为int向下取整的除法是两个斜线‘//’。

3.2.2 类

python3中所有类派生自object类。
python2中不是这样的???好吧。。。

3.2.3 字符串与二进制

python2中用str对象表示字符串和二进制,用unicode对象表示unicode。
python3中用bytes对象表示二进制,用str对象表示一切text。

3.2.4 print

print从一个表达式变成了一个函数。所以在python3里,print需要加括号。像python2里那个的语法将报错。

3.2.5 异常捕获

在python3,多个异常类型,需要用括号括起来,如:

>>> import sys
>>> try:
...     a = 1/'0'
... except (ZeroDivisionError, TypeError):

3.2.6 int和long

在python3里,int和long类型被合并。在数组后边加后缀L的语法会报错,如:

“1024L”

在python3里,0开头的数字也会报错。0o开头代表8进制,0x开头代表16进制。

3.2.7 unicode和binary

在python3里,
尽管这两个语法也好使:

u"", b""

但应该尽量选择用下面这种:

u(), b()

3.2.8 C扩展时的区别

python2的C扩展与python3不同,然后python2的本来我就不熟。略。

3.2.9 缩进

在python2里,一个tab和8个空格可能对等互换。也就是说在python2里,你可以一个tab和8个空格混用来缩进
解释器也不会报错。
在python3里,这样是不用的。一个tab只能与一个tab等价。

3.3 所有python2与python3之间的不同

differences


好了,现在可以快乐的python3了。

原文地址:https://www.cnblogs.com/hugetong/p/10299097.html