zhyq0826 / zhyq0826.github.io

三月沙的博客
http://sanyuesha.com
6 stars 1 forks source link

python 2 to 3 #118

Closed zhyq0826 closed 5 years ago

zhyq0826 commented 6 years ago

http://python-future.org/compatible_idioms.html#stringio http://portingguide.readthedocs.io/en/latest/builtins.html https://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

移除所有字符串异常

In any case you should remove all usage of string exceptions in your code and make it run under Python 2.6 before doing anything else.

raise "exception" ==> raise Exception("exception")

在 python 2 下用 -3 option 执行程序

The next step is to run your code under Python 2.6 or Python 2.7 with the -3 option.

使用 // 替代 / 做整数除法

在 python 2 中 整数除法返回整数,即商,但是 python 3 返回 float

python2

>>> 5/2
2

python3

>>> 5/2
2.5

使用新式类

区分 binary data 和 strings

在 python2 中可以使用 str 装在 binary data 和 text,str 和 Unicode,但是 python3 中 binary data 是 bytes,str for text,无论 text 是不是 Unicode,在 python 3 中 str 和 python2 中的 Unicode 类似,而 byte type 和 str 类似。

首先不能混用 str ,也就是不能在 python 2 中用 str 做 binary data 和 text,因为不同类型是不能进行比较的

排序时使用 key 而不是 cmp

不要使用任何被移除的 module

Optional: Use the iterator-methods on dictionaries

python 3 中的 dict 返回的是迭代器,而不是 list