Python print函数全面解析
在Python中,print() 是一个非常基础且常用的内置函数,用于将指定的信息输出到控制台。
1. 基本语法
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
2. 参数详解
2.1 位置参数 (*objects)
print(1, 2.0, "three", [4], {'five': 5})
# 输出: 1 2.0 three [4] {'five': 5}
2.2 sep 参数
print(1, 2, 3, sep='|') # 输出: 1|2|3
print(1, 2, 3, sep='') # 输出: 123
2.3 end 参数
print("Hello", end=' ')
print("World") # 输出: Hello World
2.4 file 参数
with open('output.txt', 'w') as f:
print("Hello file", file=f)
2.5 flush 参数
import time
print("Loading", end='', flush=True)
for _ in range(5):
print(".", end='', flush=True)
time.sleep(1)
3. 高级用法
3.1 格式化输出
name = "Alice"
age = 25
# 旧式格式化
print("Name: %s, Age: %d" % (name, age))
# str.format()
print("Name: {}, Age: {}".format(name, age))
# f-string (Python 3.6+)
print(f"Name: {name}, Age: {age}")
3.2 打印到stderr
import sys
print("Error message", file=sys.stderr)
3.3 控制台颜色输出
# ANSI转义码
print("\033[31mRed Text\033[0m") # 红色文本
print("\033[42mGreen Background\033[0m") # 绿色背景
3.4 动态进度条
import time
for i in range(101):
print(f"\rProgress: {i}%", end='', flush=True)
time.sleep(0.1)
4. 底层原理
-
print()实际上是对sys.stdout.write()的高级封装 -
调用流程:
- 将所有对象转换为字符串(调用
str()) - 用
sep连接这些字符串 - 添加
end字符串 - 调用
file.write()写入结果 - 如果
flush为True,则调用file.flush() -
可以重定向
sys.stdout来改变默认输出行为:import sys class CustomOutput: def write(self, text): # 自定义处理逻辑 pass sys.stdout = CustomOutput() print("This goes to custom output")
5. 性能考虑
-
大量小数据打印时,考虑先构建完整字符串再一次性打印
# 较差的方式 for item in large_list: print(item) # 更好的方式 print('\n'.join(map(str, large_list))) -
在性能关键代码中,直接使用
sys.stdout.write()可能更快
6. 调试技巧
- 临时重定向输出用于调试:
from io import StringIO import sys old_stdout = sys.stdout sys.stdout = mystdout = StringIO() # 执行一些操作 print("Debug info") # 恢复并获取输出 sys.stdout = old_stdout debug_info = mystdout.getvalue()
作者:门前灯