速查表
Python2 vs Python3
| Name | Python2 | Python3 | Addtion Info |
|---|---|---|---|
| try | try except ValueError, e | try except ValueError as e | |
| exception | ValueError(‘aa’).message | - | python3中可用ValueError(‘aa’).args[0] 替代 |
__import__ |
__import__ |
__import__ |
推荐importlib.import_module替代,可移植性更好 |
| 关键字 | 函数 | ||
| unicode | unicode | str | python2默认的string是bytes, Python3中是unicode |
| bytes | str | bytes | |
| division | 1 / 2 | 1 // 2 | |
| division | 1 / 2.0 | 1 / 2 | |
| 不等于操作符 | <> | != | 这个操作费在Python3中已废弃,使用!=替代 |
| round | round(0.5) == 1.0 | round(0.5) == 0 | Python3内建的 round 是四舍六入五成双的机制 |
| xrange | xrange | range | |
| range | range(1,2) | list(range(1,2)) | |
| reduce | reduce | - | Python使用functools.reduce替代 |
| dict.keys | dict.keys() | list(dict.keys()) | python的dict遍历不保证顺序, 同一个字典py2和py3的遍历顺序可能不一样 |
| dict.iterkeys | dict.iterkeys() | dict.keys() | |
| dict.items | dict.items() | list(dict.items()) | |
| dict.iteritems | dict.iteritems() | dict.items() | |
| 内置库 | commands | - | 用subprocess替代 |
| 内置库 | sys.setdefaultencoding | - | |
| 内置库 | Queue | queue | |
| 内置库 | ConfigParser | configparser |
详细对比
unicode
Python2
- 字符串分
str('')和unicode(u'') - str,就是以
'xxx'形式输入的字符,实际储存的值是xxx经过系统默认字符集encode过的字节串(bytes),如’\xe8\x86\x9c’ - unicode,就是以
u'xxx'形式输入的字符,实际储存的值是xxx对应的unicode码, 如u'\u819c' - str,其实等于python3中的字节串(bytes)
- unicode,其实等于python3中的字符串(str)
- 在python2中unicode才是真正的字符串
1 | '膜法' |
Python3
1 | '膜法' |
文件读写
open函数,与unicode的问题是相关联的
- python2的文件读写都是操作bytes的
- python3的文件读写,默认是
t(文本)模式的,操作的是unicode,并以utf8作为默认编码
python2
1 | aa = open('/mnt/d/11.txt', 'r') |
python3
1 | aa = open('/mnt/d/11.txt', 'r') # 11.txt is saved as utf8 |