Python字符串格式化是编程中的基础且重要的操作。str.format()方法作为Python 2.6引入的字符串格式化方式在Python 3中成为主流格式化方法之一。本报告将深入探讨str.format()方法的使用方式、语法特性、应用场景并通过丰富的代码示例展示其强大功能。1. 引言在Python编程中字符串格式化是将变量、表达式或值插入到字符串中的过程。Python提供了多种字符串格式化方法包括%操作符格式化C风格str.format()方法f-stringPython 3.6其中str.format()方法因其灵活性和可读性成为Python开发者广泛使用的格式化方式。2. str.format()基础语法str.format()方法的基本语法如下字符串{}.format(值)其中{}是占位符用于指定插入值的位置。2.1 基本用法示例# 单个占位符nameAlicegreetingHello, {}!.format(name)print(greeting)# 输出: Hello, Alice!# 多个占位符first_nameJohnlast_nameDoefull_name{} {}.format(first_name,last_name)print(full_name)# 输出: John Doe# 不同类型的数据age25height1.75info姓名: {}, 年龄: {}, 身高: {}米.format(张三,age,height)print(info)# 输出: 姓名: 张三, 年龄: 25, 身高: 1.75米3. 位置参数与索引str.format()方法支持通过索引指定参数的位置这使得参数的重用和重新排序成为可能。3.1 位置参数# 使用位置参数print({} {}.format(Hello,World))# 输出: Hello Worldprint({1} {0}.format(Hello,World))# 输出: World Helloprint({0} {1} {0}.format(Hello,World))# 输出: Hello World Hello3.2 索引重用# 重用参数template姓名: {0}, 年龄: {1}, 姓名再次: {0}resulttemplate.format(李四,30)print(result)# 输出: 姓名: 李四, 年龄: 30, 姓名再次: 李四4. 关键字参数除了位置参数str.format()还支持关键字参数使代码更具可读性。# 使用关键字参数person姓名: {name}, 年龄: {age}, 城市: {city}.format(name王五,age28,city北京)print(person)# 输出: 姓名: 王五, 年龄: 28, 城市: 北京# 混合使用位置和关键字参数mixed第一个: {0}, 第二个: {second}, 第三个: {1}.format(A,C,secondB)print(mixed)# 输出: 第一个: A, 第二个: B, 第三个: C5. 格式化规范str.format()方法提供了丰富的格式化规范可以控制数据的显示方式。5.1 数字格式化# 整数格式化print({:d}.format(42))# 输出: 42print({:5d}.format(42))# 输出: 42 (右对齐宽度为5)print({:05d}.format(42))# 输出: 00042 (用0填充宽度为5)# 浮点数格式化print({:.2f}.format(3.14159))# 输出: 3.14 (保留2位小数)print({:10.2f}.format(3.14159))# 输出: 3.14 (宽度10保留2位小数)print({:.2f}.format(3.14159))# 输出: 3.14 (显示正负号)print({:.0f}.format(3.14159))# 输出: 3 (不显示小数部分)# 百分比格式化print({:.2%}.format(0.856))# 输出: 85.60%print({:.1%}.format(0.1))# 输出: 10.0%# 科学计数法print({:.2e}.format(1234567))# 输出: 1.23e06print({:.2E}.format(1234567))# 输出: 1.23E065.2 字符串格式化# 字符串对齐textPythonprint({:10}.format(text))# 输出: Python (左对齐宽度10)print({:10}.format(text))# 输出: Python (右对齐宽度10)print({:^10}.format(text))# 输出: Python (居中对齐宽度10)print({:*^10}.format(text))# 输出: **Python** (居中用*填充)# 截断字符串long_textHello, World!print({:.5}.format(long_text))# 输出: Hello (截取前5个字符)print({:10.5}.format(long_text))# 输出: Hello (宽度10截取5个字符)5.3 进制转换# 不同进制表示number255print({:b}.format(number))# 输出: 11111111 (二进制)print({:o}.format(number))# 输出: 377 (八进制)print({:x}.format(number))# 输出: ff (十六进制小写)print({:X}.format(number))# 输出: FF (十六进制大写)print({:#b}.format(number))# 输出: 0b11111111 (带前缀的二进制)print({:#x}.format(number))# 输出: 0xff (带前缀的十六进制)6. 对象属性访问str.format()方法可以访问对象的属性和方法。# 访问对象属性classPerson:def__init__(self,name,age):self.namename self.ageage personPerson(赵六,35)info姓名: {p.name}, 年龄: {p.age}.format(pperson)print(info)# 输出: 姓名: 赵六, 年龄: 35# 访问字典键值data{name:孙七,age:40,city:上海}info姓名: {d[name]}, 年龄: {d[age]}, 城市: {d[city]}.format(ddata)print(info)# 输出: 姓名: 孙七, 年龄: 40, 城市: 上海7. 高级用法7.1 动态格式化# 动态宽度和精度width15precision3value3.1415926formatted{:{width}.{precision}f}.format(value,widthwidth,precisionprecision)print(formatted)# 输出: 3.142# 动态对齐方式alignment# 左对齐text测试result{:{}10}.format(text,alignment)print(result)# 输出: 测试 (左对齐宽度10)7.2 嵌套格式化# 嵌套格式化data[{name:Alice,score:95.5},{name:Bob,score:87.3},{name:Charlie,score:92.8}]header{:10} {:6}.format(姓名,成绩)print(header)print(-*18)foritemindata:row{:10} {:6.1f}.format(item[name],item[score])print(row)# 输出:# 姓名 成绩# ------------------# Alice 95.5# Bob 87.3# Charlie 92.87.3 日期时间格式化fromdatetimeimportdatetime nowdatetime.now()formatted_date当前时间: {:%Y-%m-%d %H:%M:%S}.format(now)print(formatted_date)# 输出: 当前时间: 2023-10-05 14:30:45 (示例)# 单独格式化日期和时间date_only日期: {:%Y年%m月%d日}.format(now)time_only时间: {:%H时%M分%S秒}.format(now)print(date_only)# 输出: 日期: 2023年10月05日print(time_only)# 输出: 时间: 14时30分45秒8. 实际应用示例8.1 生成报表# 销售报表生成sales_data[{product:产品A,quantity:100,price:25.50},{product:产品B,quantity:150,price:18.75},{product:产品C,quantity:75,price:42.00}]# 报表标题print(*50)print({:^46}.format(销售报表))print(*50)# 表头header{:10} {:8} {:10} {:12}.format(产品,数量,单价,总价)print(header)print(-*50)# 数据行total_sales0foriteminsales_data:totalitem[quantity]*item[price]total_salestotal row{:10} {:8} {:10.2f} {:12.2f}.format(item[product],item[quantity],item[price],total)print(row)print(-*50)print({:42}.format(总计: {:.2f}.format(total_sales)))print(*50)8.2 日志格式化importloggingfromdatetimeimportdatetime# 自定义日志格式classCustomFormatter(logging.Formatter):defformat(self,record):log_format[{asctime}] [{levelname:8}] {message}.format(asctimeself.formatTime(record,datefmt%Y-%m-%d %H:%M:%S),levelnamerecord.levelname,messagerecord.getMessage())returnlog_format# 配置日志loggerlogging.getLogger(__name__)logger.setLevel(logging.DEBUG)handlerlogging.StreamHandler()handler.setFormatter(CustomFormatter())logger.addHandler(handler)# 使用日志logger.info(系统启动)logger.warning(内存使用率超过80%)logger.error(数据库连接失败)9. 与其他格式化方法比较9.1 与%操作符比较# %操作符格式化nameAliceage25old_style姓名: %s, 年龄: %d%(name,age)# str.format()格式化new_style姓名: {}, 年龄: {}.format(name,age)# f-string格式化 (Python 3.6)f_stringf姓名:{name}, 年龄:{age}print(old_style)# 输出: 姓名: Alice, 年龄: 25print(new_style)# 输出: 姓名: Alice, 年龄: 25print(f_string)# 输出: 姓名: Alice, 年龄: 259.2 优缺点分析str.format()的优点语法清晰易于阅读支持位置参数和关键字参数提供丰富的格式化选项可以重用参数支持对象属性访问str.format()的缺点相比f-string语法稍显冗长性能略低于f-string10. 最佳实践选择合适的格式化方法对于简单场景f-string更简洁对于复杂场景或需要动态构建格式字符串时str.format()更灵活。使用关键字参数提高可读性当参数较多时使用关键字参数可以使代码更易理解。注意性能在循环中频繁使用字符串格式化时考虑性能影响。处理异常确保提供的参数数量和类型与占位符匹配避免运行时错误。国际化考虑对于多语言应用考虑使用专门的国际化库。11. 结论str.format()方法是Python中强大而灵活的字符串格式化工具。它提供了丰富的格式化选项支持位置参数、关键字参数、对象属性访问等特性适用于各种字符串格式化需求。虽然Python 3.6引入的f-string在某些场景下更简洁但str.format()仍然因其灵活性和向后兼容性而在Python编程中占据重要地位。掌握str.format()方法的使用能够帮助开发者编写更清晰、更灵活的代码提高开发效率和代码质量。在实际项目中根据具体需求选择合适的字符串格式化方法是Python开发者应具备的基本技能。