print() 是 Python 中最基础也最常用的函数之一,但它远比大多数人想象的更强大。下面我将全面解析 print() 的所有参数,并展示各种实用调试技巧。
print() 基本语法print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)*objects:要打印的对象(可变参数)print(1, 2.0, "three", [4], {"five": 5})
# 输出: 1 2.0 three [4] {'five': 5}sep:分隔符(默认空格)print(1, 2, 3, sep=', ') # 输出: 1, 2, 3
print(1, 2, 3, sep=' → ') # 输出: 1 → 2 → 3
print(1, 2, 3, sep='') # 输出: 123end:结束符(默认换行)print("Hello", end=' ')
print("World") # 输出: Hello World
print("Loading", end='... ')
print("Done") # 输出: Loading... Donefile:输出目标(默认sys.stdout)with open('output.txt', 'w') as f:
print("保存到文件", file=f)flush:强制刷新(默认False)import time
print("进度:", end=' ')
for i in range(10):
print(f"{i*10}%", end=' ', flush=True)
time.sleep(0.5)x = 10
y = 20
print(f"{x=}, {y=}") # 输出: x=10, y=20这是Python 3.8及以上版本新增的f-string调试语法。在f-string中使用 {变量=} 的格式时,会自动输出“变量名=值”的字符串,方便快速调试查看变量名和对应的值,无需手动写 "x=" + str(x) 这类拼接代码。
def debug_print(*args):
import inspect
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
print(f"[{info.filename}:{info.lineno}]", *args)
debug_print("变量值:", x) # 输出: [example.py:10] 变量值: 10from datetime import datetime
def timestamp_print(*args):
now = datetime.now().strftime("%H:%M:%S.%f")[:-3]
print(f"[{now}]", *args)
timestamp_print("程序启动") # 输出: [14:25:36.452] 程序启动def color_print(text, color='red'):
colors = {
'red': '\033[91m',
'green': '\033[92m',
'yellow': '\033[93m',
'blue': '\033[94m',
'end': '\033[0m'
}
print(f"{colors[color]}{text}{colors['end']}")
color_print("错误信息", 'red')
color_print("成功信息", 'green')data = [
["Alice", 25, "Engineer"],
["Bob", 30, "Designer"],
["Charlie", 35, "Manager"]
]
print("\n{:<10} {:<5} {:<10}".format("Name", "Age", "Job"))
for row in data:
print("{:<10} {:<5} {:<10}".format(*row))import time
print("进度: [", end='')
for i in range(20):
print("#", end='', flush=True)
time.sleep(0.1)
print("] 完成!")with open('log.txt', 'w') as log_file, open('console.txt', 'w') as console_file:
print("调试信息", file=log_file)
print("用户输出", file=console_file)
print("双重输出", file=log_file) # 只写入log文件
print("双重输出") # 同时显示在控制台import sys
print("错误信息", file=sys.stderr)def no_print(*args, **kwargs):
pass
print = no_print # 禁用所有print
print("这不会显示") # 无输出def indent_print(text, level=0):
print(" " * level + text)
indent_print("开始处理")
indent_print("步骤1", 1)
indent_print("子步骤1.1", 2)