Python format()函数高级字符串格式化详解
文章目录
- Python `format()`函数高级字符串格式化详解
Python format()
函数高级字符串格式化详解
format()
是Python中功能强大的字符串格式化工具,它提供了比传统%
格式化更灵活、更强大的方式来处理字符串格式化。下面我将从基础到高级全面讲解format()
函数的使用方法。
一、format()
函数基础用法
1. 基本语法
\"模板字符串\".format(参数1, 参数2, ...)
2. 三种基本使用方式
(1) 位置参数
print(\"{}的{}成绩是{}\".format(\"张三\", \"数学\", 95))# 输出: 张三的数学成绩是95
(2) 索引参数
print(\"{0}的{2}成绩是{1}\".format(\"张三\", 95, \"数学\"))# 输出: 张三的数学成绩是95
(3) 命名参数
print(\"{name}的{subject}成绩是{score}\".format( name=\"李四\", subject=\"英语\", score=88))# 输出: 李四的英语成绩是88
二、数字格式化
1. 基本数字格式化语法
\"{:[填充][对齐][符号][宽度][,][.精度][类型]}\".format(数字)
2. 常用数字格式化示例
{:.2f}
\"{:.2f}\".format(3.14159)
3.14
{:,}
\"{:,}\".format(1234567)
1,234,567
{:.2%}
\"{:.2%}\".format(0.4567)
45.67%
{:x}
\"{:x}\".format(255)
ff
{:b}
\"{:b}\".format(10)
1010
{:.2e}
\"{:.2e}\".format(123456)
1.23e+05
3. 对齐与填充
{:10}
\"{:10}\".format(123)
123
{:<10}
\"{:<10}\".format(123)
123
{:^10}
\"{:^10}\".format(123)
123
{:010}
\"{:010}\".format(123)
0000000123
{:*^10}
\"{:*^10}\".format(123)
***123****
# 综合示例:银行金额显示amount = 1234567.8912print(\"账户余额: {:,.2f}元\".format(amount))# 输出: 账户余额: 1,234,567.89元
三、字符串格式化
1. 字符串对齐与截断
{:>10}
\"{:>10}\".format(\"hello\")
hello
{:<10}
\"{:<10}\".format(\"hello\")
hello
{:^10}
\"{:^10}\".format(\"hello\")
hello
{:.3}
\"{:.3}\".format(\"hello\")
hel
2. 填充与对齐结合
# 表格格式化示例data = [(\"苹果\", 5.5, 10), (\"香蕉\", 3.2, 8), (\"橙子\", 4.8, 15)]for item in data: print(\"{:5.2f}元 库存: {:03d}\".format(*item)) # 输出:# 苹果 单价: 5.50元 库存: 010# 香蕉 单价: 3.20元 库存: 008# 橙子 单价: 4.80元 库存: 015
四、高级格式化技巧
1. 访问对象属性
class Person: def __init__(self, name, age): self.name = name self.age = agep = Person(\"王五\", 30)print(\"{0.name}今年{0.age}岁\".format(p))# 输出: 王五今年30岁
2. 访问字典元素
data = {\"name\": \"赵六\", \"score\": 92}print(\"学生{name}的成绩是{score}\".format(**data))# 输出: 学生赵六的成绩是92
3. 访问列表元素
items = [\"手机\", \"电脑\", \"平板\"]print(\"产品1: {0[0]}, 产品2: {0[1]}\".format(items))# 输出: 产品1: 手机, 产品2: 电脑
4. 动态格式化
# 根据条件动态设置格式for num in [123, 12345, 1234567]: print(\"{:{align}{width},}\".format(num, align=\">\", width=10)) # 输出:# 123# 12,345# 1,234,567
五、特殊格式化
1. 大括号转义
# 显示大括号本身print(\"{{}}是format使用的括号\".format())# 输出: {}是format使用的括号
2. 日期时间格式化
from datetime import datetimenow = datetime.now()print(\"{:%Y-%m-%d %H:%M:%S}\".format(now))# 输出: 2023-08-15 14:30:45 (当前时间)
3. 自定义格式化
class Temperature: def __init__(self, celsius): self.celsius = celsius def __format__(self, format_spec): if format_spec == \"f\": return f\"{self.celsius * 9/5 + 32:.1f}°F\" return f\"{self.celsius:.1f}°C\"temp = Temperature(25)print(\"温度: {:f}\".format(temp)) # 输出: 温度: 77.0°Fprint(\"温度: {}\".format(temp)) # 输出: 温度: 25.0°C
六、性能比较
1. 各种格式化方式对比
2. 何时使用format()
✅ 适合场景:
- Python 2.6到3.5版本
- 需要复用格式模板
- 复杂的格式化需求
- 需要动态格式字符串
❌ 不适合场景:
- Python 3.6+简单格式化(用f-string更好)
- 极高性能要求的场景
七、实际应用案例
案例1:生成报表
# 销售报表生成sales_data = [ (\"笔记本电脑\", 12, 5999.99), (\"智能手机\", 25, 3999.50), (\"平板电脑\", 8, 2999.00)]# 表头print(\"{:10} {:>15} {:>15}\".format( \"产品名称\", \"销售数量\", \"单价\", \"总金额\"))print(\"-\" * 60)# 表格内容for product, quantity, price in sales_data: total = quantity * price print(\"{:10d} {:>15,.2f} {:>15,.2f}\".format( product, quantity, price, total))# 输出示例:# 产品名称 销售数量 单价 总金额# ------------------------------------------------------------# 笔记本电脑 12 5,999.99 71,999.88# 智能手机 25 3,999.50 99,987.50# 平板电脑 8 2,999.00 23,992.00
案例2:日志格式化
def log_message(level, message): timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") print(\"[{:<5}] {:<20} {}\".format(level, timestamp, message))log_message(\"INFO\", \"系统启动完成\")log_message(\"ERROR\", \"文件打开失败\")# 输出示例:# [INFO ] 2023-08-15 14:45:30 系统启动完成# [ERROR] 2023-08-15 14:46:12 文件打开失败
八、总结
format()
函数核心要点:
- 基本用法:位置参数
{}
、索引参数{0}
、命名参数{name}
- 数字格式化:
- 精度控制:
{:.2f}
- 千分位:
{:,}
- 对齐填充:
{:0>10}
- 精度控制:
- 字符串格式化:对齐
{:<10}
、截断{:.5}
- 高级特性:
- 访问对象属性
{obj.attr}
- 动态格式
{:{width}}
- 自定义
__format__
方法
- 访问对象属性
- 特殊格式:日期时间、大括号转义
format()
提供了Python中最强大、最灵活的字符串格式化能力,特别适合需要复杂格式控制的场景。虽然Python 3.6+引入了更简洁的f-string,但在需要复用格式模板或兼容旧版本Python时,format()
仍然是不可或缺的工具。