01 - Python 常见版本兼容性问题
中文处理
如果在 Python 脚本中出现了中文,需要在 shebang 下添加一行:
# -*- coding: utf-8 -*-
字符编码
- Python 2 的默认字符编码为 ascii;
- Python 3 的默认字符编码为 utf-8;
print
- 在 Python 2 下,
print
是一个内置语句,通过print "string"
的方式使用; - 在 Python 3 下,
print
是一个内置函数,通过print("string")
的方式使用。
- Python 2.x
- Python 3.x
- Python 2.6+
print "blah blah"
print("blah blah")
from __future__ import print_function
print("blah blah", 123)
字符串格式化
- All versions
- Python 2.6+
- Python 2.7+
"str: %s, int: %d." % ("string", 10)
"str: {0}, int: {1}.".format("string", 10)
"str: {}, int: {}.".format("string", 10)
整数除法
- Python 2 下,两个整数相除总是返回整数;
- Python 3 下,除法总是返回浮点数。
希望返回整数:
- Python 2.x
- All versions
3 / 2
type(3 / 2)
3 // 2
type(3 // 2)
希望返回浮点数:
- All versions
- Python 3.x
3 * 1.0 / 2
type(3 * 1.0 / 2)
3 / 2
type(3 / 2)
异常处理
- Python 2.x
- Python 2.6+
try:
raise TypeError, "类型错误"
except TypeError, error:
print(error)
try:
raise TypeError("类型错误")
except TypeError as error:
print(error)