本文目录导读:

我来详细讲解Python中的字符串格式化输出方法。
旧式格式化 操作符
# 基本用法
name = "Alice"
age = 25
print("姓名: %s, 年龄: %d" % (name, age))
# 格式化符号
print("%.2f" % 3.14159) # 保留2位小数: 3.14
print("%10s" % "hello") # 右对齐,宽度10
print("%-10s" % "hello") # 左对齐,宽度10
print("%05d" % 42) # 数字补零: 00042
str.format() 方法 (推荐)
# 基本用法
name = "Bob"
age = 30
print("姓名: {}, 年龄: {}".format(name, age))
# 索引指定
print("{0} 喜欢 {1}".format("Alice", "篮球")) # Alice 喜欢 篮球
print("{1} 喜欢 {0}".format("Alice", "篮球")) # 篮球 喜欢 Alice
# 关键字参数
print("{name} 年龄 {age}".format(name="Charlie", age=35))
# 格式化数字
print("{:.2f}".format(3.14159)) # 3.14
print("{:>10}".format("hello")) # 右对齐
print("{:<10}".format("hello")) # 左对齐
print("{:^10}".format("hello")) # 居中对齐
print("{:010d}".format(42)) # 补零: 0000000042
f-string (Python 3.6+) - 最推荐
name = "David"
age = 28
print(f"姓名: {name}, 年龄: {age}")
# 表达式计算
print(f"明年年龄: {age + 1}")
print(f"{name.upper()} 你好")
# 格式化数字
pi = 3.1415926
print(f"{pi:.3f}") # 3.142
print(f"{pi:.3e}") # 科学计数法: 3.142e+00
print(f"{pi:.2%}") # 百分比: 314.16%
# 对齐
text = "hi"
print(f"{text:>10}") # 右对齐
print(f"{text:<10}") # 左对齐
print(f"{text:^10}") # 居中
# 填充字符
print(f"{text:*^10}") # ****hi****
print(f"{text:*>10}") # ********hi
print(f"{text:*<10}") # hi********
# 数字格式化
num = 1234567890
print(f"{num:,}") # 1,234,567,890
print(f"{num:_}") # 1_234_567_890
# 二进制、八进制、十六进制
value = 255
print(f"二进制: {value:#b}") # 0b11111111
print(f"八进制: {value:#o}") # 0o377
print(f"十六进制: {value:#x}") # 0xff
高级格式化技巧
# 字典解包
person = {"name": "Eve", "age": 22}
print("姓名: {name}, 年龄: {age}".format(**person))
# f-string 中的字典访问
print(f"姓名: {person['name']}, 年龄: {person['age']}")
# 日期格式化
from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}") # 2024-01-15 14:30:00
print(f"{now:今天是%A}") # 今天是Monday
# 条件表达式
score = 85
print(f"{'及格' if score >= 60 else '不及格'}")
# 复杂对齐
data = [
("Alice", 25, 50000),
("Bob", 30, 60000),
("Charlie", 35, 70000)
]
# 打印表格
print(f"{'姓名':<10}{'年龄':<10}{'薪资':<10}")
for name, age, salary in data:
print(f"{name:<10}{age:<10}{salary:<10,}")
性能对比
import timeit
name = "Alice"
age = 25
# % 格式化
time1 = timeit.timeit('"姓名: %s, 年龄: %d" % (name, age)', globals=globals())
# format 方法
time2 = timeit.timeit('"姓名: {}, 年龄: {}".format(name, age)', globals=globals())
# f-string
time3 = timeit.timeit('f"姓名: {name}, 年龄: {age}"', globals=globals())
print(f"%格式化: {time1:.6f}")
print(f"format: {time2:.6f}")
print(f"f-string: {time3:.6f}")
最佳实践建议
- Python 3.6+ 优先使用 f-string - 性能最好,可读性最强
- 需要延迟计算时使用
.format()- 如日志模板 - 兼容旧版 Python 使用 格式化
- 格式化数字时使用格式化说明符
- 使用
repr()和str()的区别
# 使用 !r 和 !s 强制转换
value = "hello\nworld"
print(f"{value!r}") # 带引号: 'hello\nworld'
print(f"{value!s}") # 正常字符串: hello
# world
这些方法能满足绝大部分字符串格式化需求,选择最适合项目需求的就好。