在 Python 中,有多种方式可以进行字符串的格式化输出,下面为你详细介绍常见的几种方法。
这是 Python 早期就支持的字符串格式化方式,使用 %
操作符结合不同的格式化符号来实现。
%s
:用于格式化字符串。
%d
:用于格式化整数。
%f
:用于格式化浮点数。
name = "Alice"
print("My name is %s." % name)
age = 25
print("I am %d years old." % age)
height = 1.65
print("My height is %.2f meters." % height)
print("My name is %s, and I am %d years old." % (name, age))
str.format()
是 Python 2.6 及以上版本引入的一种更灵活、更强大的字符串格式化方式。
"格式化字符串".format(值1, 值2, ...)
可以通过位置来指定要插入的值。
print("My name is {}, and I am {} years old.".format("Bob", 30))
使用关键字来指定要插入的值。
print("My name is {name}, and I am {age} years old.".format(name="Charlie", age=35))
可以通过索引来指定要插入的值的位置。
print("My name is {1}, and I am {0} years old.".format(40, "David"))
可以对数值进行格式化,如指定宽度、精度等。
print("The value is {:.2f}".format(3.14159))
f - 字符串是 Python 3.6 及以上版本引入的一种简洁且直观的字符串格式化方式,在字符串前加 f
或 F
,并在 {}
中直接使用变量名。
name = "Eve"
age = 22
print(f"My name is {name}, and I am {age} years old.")
height = 1.72
print(f"My height is {height:.2f} meters.")
string.Template
类提供了一种简单的字符串替换机制,使用 $
符号来标识变量。
from string import Template
template = Template("格式化字符串")
result = template.substitute(变量名=值)
from string import Template
name = "Frank"
age = 28
template = Template("My name is $name, and I am $age years old.")
print(template.substitute(name=name, age=age))
- 旧式字符串格式化(% 操作符):语法简单,但不够灵活,适合简单的格式化需求。
- 新式字符串格式化(
str.format()
方法):功能强大,支持位置参数、关键字参数、索引参数等多种方式,适用于各种复杂的格式化场景。
- f - 字符串:语法简洁,直观易用,性能较高,是 Python 3.6 及以上版本推荐使用的格式化方式。
string.Template
类:语法简单,安全性高,适合需要从外部获取模板字符串的场景。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下