本文将深入探讨Python中print函数的各种用法,从基础输出到高级格式化技巧,帮助开发者掌握变量输出的精髓。
目录
基础语法与核心概念
Python的print()函数是最常用的内置函数之一,用于将信息输出到控制台。其基本语法看似简单,实则蕴含丰 富的功能。
基本语法结构
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)参数说明:
*objects:要输出的对象,可以接受多个参数sep:分隔符,默认为空格end:结束符,默认为换行符file:输出目标,默认为标准输出flush:是否立即刷新输出缓冲区
最简单的输出示例
# 基础字符串输出
print("Hello, World!")
# 输出:Hello, World!
# 数字输出
print(42)
# 输出:42
# 布尔值输出
print(True)
# 输出:True变量输出的基本方法
直接输出变量
name = "Alice"
age = 25
height = 1.68
print(name) # 输出:Alice
print(age) # 输出:25
print(height) # 输出:1.68字符串拼接输出
# 使用逗号分隔(自动添加空格)
print("Name:", name, "Age:", age)
# 输出:Name: Alice Age: 25
# 使 用字符串拼接
print("Name: " + name + ", Age: " + str(age))
# 输出:Name: Alice, Age: 25
# 使用f-string(Python 3.6+)
print(f"Name: {name}, Age: {age}")
# 输出:Name: Alice, Age: 25不同数据类型的输出
# 列表输出
fruits = ["apple", "banana", "orange"]
print(fruits) # 输出:['apple', 'banana', 'orange']
# 字典输出
person = {"name": "Bob", "city": "Beijing"}
print(person) # 输出:{'name': 'Bob', 'city': 'Beijing'}
# 元组输出
coordinates = (10, 20)
print(coordinates) # 输出:(10, 20)格式化输出技巧
1. 百分号格式化(传统方法)
# 字符串格式化
print("Hello, %s!" % name)
# 输出:Hello, Alice!
# 整数格式化
print("Age: %d" % age)
# 输出:Age: 25
# 浮点数格式化
print("Height: %.2f meters" % height)
# 输出:Height: 1.68 meters
# 多个变量格式化
print("%s is %d years old and %.2f meters tall" % (name, age, height))
# 输出:Alice is 25 years old and 1.68 meters tall2. str.format()方法
# 位置参数
print("Hello, {}!".format(name))
# 输出:Hello, Alice!
# 命名参数
print("Hello, {name}! You are {age} years old.".format(name=name, age=age))
# 输出:Hello, Alice! You are 25 years old.
# 格式控制
print("Pi: {:.2f}".format(3.1415926))
# 输出:Pi: 3.14
# 对齐和宽度
print("|{:>10}|{:<10}|{:^10}|".format("right", "left", "center"))
# 输出:| right|left | center |3. f-string格式化(推荐方法)
# 基本用法
print(f"Hello, {name}!")
# 输出:Hello, Alice!
# 表达式计算
print(f"Next year, {name} will be {age + 1} years old")
# 输出:Next year, Alice will be 26 years old
# 格式规范
import math
print(f"Pi with 4 decimals: {math.pi:.4f}")
# 输出:Pi with 4 decimals: 3.1416
# 百分比格式
ratio = 0.85
print(f"Success rate: {ratio:.1%}")
# 输出:Success rate: 85.0%
# 千位分隔符
large_number = 1234567
print(f"Large number: {large_number:,}")
# 输出:Large number: 1,234,5674. 高级格式化技巧
# 日期时间格式化
from datetime import datetime
now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")
# 输出:Current time: 2025-10-23 07:38:45
# 科学计数法
print(f"Scientific: {1234.5678:.2e}")
# 输出:Scientific: 1.23e+03
# 二进制、八进制、十六进制
number = 42
print(f"Binary: {number:b}, Octal: {number:o}, Hex: {number:x}")
# 输出:Binary: 101010, Octal: 52, Hex: 2a多变量同时输出
使用sep参数控制分隔符
# 默认空格分隔
print(name, age, height)
# 输出:Alice 25 1.68
# 自定义分隔符
print(name, age, height, sep=" | ")
# 输出:Alice | 25 | 1.68
# 无分隔符
print(name, age, height, sep="")
# 输出:Alice251.68
# 换行分隔
print(name, age, height, sep="\n")
# 输出:
# Alice
# 25
# 1.68使用end参数控制结束符
# 默认换行
print("Line 1")
print("Line 2")
# 输出:
# Line 1
# Line 2
# 不换行
print("Hello ", end="")
print("World!")
# 输出:Hello World!
# 自定义结束符
print("Processing", end="...")
print("Done!")
# 输出:Processing...Done!动态生成输出内容
# 使用列表展开
items = ["apple", "banana", "orange"]
print(*items)
# 输出:apple banana orange
# 使用字典展开
data = {"name": "Alice", "age": 25}
print(*data.items())
# 输出:('name', 'Alice') ('age', 25)
# 条件输出
scores = [85, 92, 78, 95]
print("High scores:", *[s for s in scores if s >= 90])
# 输出:High scores: 92 95文件输出与重定向
输出到文件
# 基本文件输出
with open("output.txt", "w", encoding="utf-8") as f:
print("Hello, File!", file=f)
print(f"Name: {name}, Age: {age}", file=f)
# 追加模式
with open("log.txt", "a", encoding="utf-8") as f:
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] User {name} logged in", file=f)