原文链接:http://www.juzicode.com/python-module-formatter
Python的Formatter模块提供强大的字符串格式化控制,支持自定义格式规范、值转换和嵌套字段处理,是构建动态文本模板和国际化应用的核心工具。
应用场景
- 动态生成结构化文本
- 本地化数字/日期格式化
- 报表模板引擎开发
- 日志消息格式定制
- API响应数据格式化
- 自定义语法解析器
安装与导入
# Python标准库无需安装
from string import Formatter
使用方法
1)基础格式化
使用位置参数和关键字参数进行基础插值
# juzicode.com/VX公众号:juzicode
from string import Formatter
fmt = Formatter()
result = fmt.format(
"欢迎访问{},今日温度:{temp}℃,时间:{time}",
"桔子code",
temp=28.5,
time="14:30"
)
print(result)
# 输出:欢迎访问桔子code,今日温度:28.5℃,时间:14:30
2)自定义格式规范
通过__format__方法实现对象自定义格式化
# juzicode.com/VX公众号:juzicode
from string import Formatter
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __format__(self, spec):
if spec == 'currency':
return f"{self.name}: ¥{self.price:.2f}"
return f"{self.name} (${self.price})"
p = Product("Python教程", 99.8)
print(f"{p}") # 输出: Python教程 ($99.8)
print(f"{p:currency}") # 输出: Python教程: ¥99.80
3)嵌套字段解析
实现字典数据的深度取值和格式化
# juzicode.com/VX公众号:juzicode
from string import Formatter
user = {
"name": "张三",
"contact": {
"email": "zhangsan@example.com",
"phone": "13800138000"
}
}
fmt = Formatter()
result = fmt.format(
"用户信息:{name},邮箱:{contact[email]},电话:{contact[phone]}",
**user
)
print(result)
# 输出:用户信息:张三,邮箱:zhangsan@example.com,电话:13800138000
4)格式转换器
使用!r,!s,!a进行repr/str/ascii转换
# juzicode.com/VX公众号:juzicode
from string import Formatter
text = "Hello\nWorld"
print(f"{text!s}") # 输出(原始文本): Hello\nWorld
print(f"{text!r}") # 输出(可打印表示): 'Hello\\nWorld'
print(f"{text!a}") # 输出(ASCII): 'Hello\\nWorld'
5)自定义解析器
继承Formatter实现模板语法解析
# juzicode.com/VX公众号:juzicode
from string import Formatter
class TemplateFormatter(Formatter):
def get_value(self, key, args, kwargs):
if key.startswith("env_"):
import os
return os.getenv(key[4:], "")
return super().get_value(key, args, kwargs)
fmt = TemplateFormatter()
result = fmt.format(
"系统信息:用户={env_USER},路径={env_PATH}",
env_USER="", env_PATH=""
)
print(result)
# 输出:系统信息:用户=root,路径=/usr/local/sbin:/usr/local/bin
6)高级数值格式化
实现财务数值的专业格式化
# juzicode.com/VX公众号:juzicode
from string import Formatter
def finance_format(value, spec):
if spec == 'cn_currency':
return f"¥{value:,.2f}"
elif spec == 'percent':
return f"{value:.2%}"
return str(value)
class FinanceFormatter(Formatter):
def format_field(self, value, format_spec):
if format_spec.startswith('finance_'):
return finance_format(value, format_spec[8:])
return super().format_field(value, format_spec)
fmt = FinanceFormatter()
result = fmt.format(
"金额:{amount:finance_cn_currency},增长率:{growth:finance_percent}",
amount=1234567.89,
growth=0.156
)
print(result)
# 输出:金额:¥1,234,567.89,增长率:15.60%
总结
Formatter核心优势:
- 提供底层格式化控制能力
- 支持深度嵌套数据结构
- 可扩展自定义格式化逻辑
注意事项:
- 复杂模板需考虑性能影响
- 字段名需与参数键名严格匹配
- 自定义解析器需处理异常情况