核心差异:print 从语句变成了函数
这是最著名、也是最容易出错的区别。

Python 2
在 Python 2 中,print 是一个语句,而不是函数,这意味着你不需要使用括号。
# Python 2 # 打印一个简单的字符串 print "Hello, World!" # 打印多个变量,用空格分隔 name = "Alice" age = 30 print name, "is", age, "years old." # 打印到文件 print >> sys.stderr, "This is an error message"
特点:
- 无括号:语法是
print [expression1, ...]。 - 尾随逗号:在末尾加上逗号 可以阻止换行。
# Python 2 for i in range(5): print i, # 输出: 0 1 2 3 4 (在同一行) >>重定向:可以使用>>将输出重定向到文件。
Python 3
在 Python 3 中,print 被改造成了函数,你必须使用括号,就像调用其他任何函数一样。
# Python 3
# 打印一个简单的字符串
print("Hello, World!")
# 打印多个变量,用空格分隔
name = "Alice"
age = 30
print(name, "is", age, "years old.")
# 打印到文件 (需要导入sys)
import sys
print("This is an error message", file=sys.stderr)
# 打印多个对象,并用指定字符连接 (sep参数)
print("A", "B", "C", sep="-") # 输出: A-B-C
特点:

- 必须使用括号:语法是
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)。 sep参数:可以指定多个输出对象之间的分隔符,默认是空格。end参数:可以指定打印结束后追加的字符串,默认是换行符\n,这替代了 Python 2 的尾随逗号功能。# Python 3 for i in range(5): print(i, end=" ") # 输出: 0 1 2 3 4 (在同一行,用空格分隔)file参数:可以指定输出目标,如sys.stderr或一个文件对象。flush参数:控制是否强制刷新输出缓冲区。
其他重要差异
input() 函数
Python 2
Python 2 有两个输入函数,这常常让初学者困惑:
-
input():不安全! 它期望用户输入的是一个合法的 Python 表达式(如字符串、数字、列表等),如果用户输入的是纯文本,程序会报错。# Python 2 # 假设用户输入 "hello" # name = input() # 会报 NameError: name 'hello' is not defined
-
raw_input():安全且常用。 它总是将用户的输入作为字符串返回,无论用户输入了什么。# Python 2 name = raw_input("Please enter your name: ") # 用户输入 "Bob" print(type(name)) # <type 'str'> print("Hello, " + name) # Hello, Bob
Python 3
Python 3 废除了 raw_input(),并将其功能合并到了 input() 中。input() 总是将用户的输入作为字符串返回,行为等同于 Python 2 的 raw_input()。
# Python 3
name = input("Please enter your name: ")
# 用户输入 "Bob"
print(type(name)) # <class 'str'>
print("Hello, " + name) # Hello, Bob
- Python 2: 用
raw_input()来获取字符串输入。 - Python 3: 用
input()来获取字符串输入。
函数定义中的 *args 和 **kwargs
在 Python 2 中,*args 和 **kwargs 的行为在 Python 3 中被标准化了,尤其是在强制关键字参数方面。
在 Python 3 中,你可以在函数参数中使用 来标记其后的所有参数都必须通过关键字传递(keyword-only arguments)。
# Python 3 特有功能
def my_function(a, b, *, c, d):
print(f"a: {a}, b: {b}, c: {c}, d: {d}")
# my_function(1, 2, 3, 4) # 会报 TypeError: my_function() takes 2 positional arguments but 4 were given
my_function(1, 2, c=3, d=4) # 正确调用
这在 Python 2 中是不支持的。
Unicode 字符串处理
在 Python 2 中,字符串有 str 和 unicode 两种类型。str 是字节串,unicode 是 Unicode 字符串。
# Python 2 s = "这是一个字符串" # str (bytes) u = u"这是一个字符串" # unicode # 如果要处理非ASCII字符,必须使用unicode,否则容易出错
在 Python 3 中,所有的字符串默认都是 Unicode 字符串(类型为 str),而字节串则被单独定义为 bytes 类型,这大大简化了字符串处理。
# Python 3
s = "这是一个字符串" # str (Unicode)
b = s.encode('utf-8') # bytes
u = b.decode('utf-8') # str (Unicode)
函数注解
Python 3 引入了函数注解,这是一种在函数定义中添加元数据(如参数和返回值的类型)的方式,但它不是强制类型检查,主要用于代码文档和静态分析工具(如 MyPy)。
# Python 3
def greet(name: str) -> str:
"""返回一个问候语"""
return "Hello, " + name
# Python 2 不支持这种语法
总结表格
| 特性 | Python 2 | Python 3 |
|---|---|---|
print |
语句,无括号print "Hello" |
函数,必须用括号print("Hello") |
| 输入函数 | input() (不安全,需表达式)raw_input() (安全,返回字符串) |
input() (安全,总是返回字符串,替代了raw_input) |
| 位置参数 | 无特殊语法 | 使用 后的参数必须为关键字参数def f(a, *, b): pass |
| 字符串 | str (字节串), unicode (Unicode) |
str (Unicode), bytes (字节串) |
| 函数注解 | 不支持 | 支持,用于类型提示def func(a: int) -> bool: |
| 除法运算 | 5 / 2 结果是 2 (整数除法)5 / 2.0 结果是 5 (浮点除法) |
5 / 2 结果是 5 (真除法)5 // 2 结果是 2 (整数除法) |
如何编写兼容 Python 2 和 3 的代码?
如果你需要编写同时兼容两个版本的代码,可以这样做:
-
使用
print函数的兼容方案: 在文件顶部引入__future__模块。from __future__ import print_function # 现在这行代码在 Python 2 和 Python 3 中都能正常工作 print("Hello, World!") -
使用
six库:six是一个专门用于帮助 Python 2 和 Python 3 代码兼容的第三方库,它提供了许多兼容性函数。# 安装 six: pip install six import six # 兼容的输入函数 name = six.moves.input("Please enter your name: ") # 兼容的 print 函数 (虽然用了 __future__,但 six 也提供了) six.print_("Hello", name) -
使用
try...except块: 对于一些无法用__future__解决的问题,可以使用try...except。try: # Python 2 import urllib2 import cookielib except ImportError: # Python 3 import urllib.request as urllib2 import http.cookiejar as cookielib
强烈建议直接使用 Python 3,Python 2 已经在 2025 年 1 月 1 日停止支持,不再接收任何安全补丁或更新,所有新的项目都应该基于 Python 3 开发,如果你需要维护旧的 Python 2 代码,了解这些差异至关重要,并且应该尽快规划将其迁移到 Python 3。
