一、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. 常用数字格式化示例
格式化需求 | 格式字符串 | 示例代码 | 输出结果 |
---|---|---|---|
保留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 |
用0填充 | {:010} | "{:010}".format(123) | 0000000123 |
用*填充 | {:*^10} | "{:*^10}".format(123) | ***123**** |
# 综合示例:银行金额显示 amount = 1234567.8912 print("账户余额: {:,.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("{:<8} 单价: {:>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 = age p = 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 datetime now = 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°f print("温度: {}".format(temp)) # 输出: 温度: 25.0°c
六、性能比较
1. 各种格式化方式对比
格式化方式 | python版本 | 可读性 | 性能 | 功能 |
---|---|---|---|---|
%格式化 | 所有版本 | 一般 | 快 | 有限 |
str.format() | 2.6+ | 好 | 中 | 强大 |
f-string | 3.6+ | 最好 | 最快 | 强大 |
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("{:<15} {:>10} {:>15} {:>15}".format( "产品名称", "销售数量", "单价", "总金额")) print("-" * 60) # 表格内容 for product, quantity, price in sales_data: total = quantity * price print("{:<15} {:>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()
函数核心要点:
1.基本用法:位置参数{}
、索引参数{0}
、命名参数{name}
2.数字格式化:
- 精度控制:
{:.2f}
- 千分位:
{:,}
- 对齐填充:
{:0>10}
3.字符串格式化:对齐{:<10}
、截断{:.5}
4.高级特性:
- 访问对象属性
{obj.attr}
- 动态格式
{:{width}}
- 自定义
__format__
方法
5.特殊格式:日期时间、大括号转义
format()
提供了python中最强大、最灵活的字符串格式化能力,特别适合需要复杂格式控制的场景。虽然python 3.6+引入了更简洁的f-string,但在需要复用格式模板或兼容旧版本python时,format()
仍然是不可或缺的工具。
以上就是python format()函数进行高级字符串格式化详解的详细内容,更多关于python format字符串格式化的资料请关注代码网其它相关文章!
发表评论