python中常见的字符串格式化方法
1. 使用 % 符号进行字符串格式化
使用 %
符号是一种较为传统的字符串格式化方法。它通过将占位符 %s
插入到字符串中,再使用 %
运算符将具体的值插入到这些占位符中。例如:
name = "Alice"
age = 20
height = 175
print("My name is %s, I'm %d years old, and my height is %.2f." % (name, age, height))
输出结果为:My name is Alice, I'm 20 years old, and my height is 175
2. 使用 format() 方法进行字符串格式化
format()
方法是一个更加灵活和推荐的字符串格式化方法。它通过 {}
占位符来表示需要插入具体值的位置,然后使用 format()
方法将这些值按顺序插入到占位符所在的位置。例如:
name = "Bob"
age = 25
height = 180.0
print("My name is {}, I'm {} years old, and my height is {:.1f}.".format(name, age, height))
输出结果为:My name is Bob, I'm 25 years old, and my height is 180.0.
3. 使用 f 字符串进行字符串格式化
从 Python 3.6 开始,还可以使用 f 字符串对表达式求值,并将结果插入到字符串中。即以 f 或 F 开头,将表达式写在 {} 中。例如:
name = "Charlie"
age = 30
height = 185
print(f"My name is {name}, I'm {age} years old, and my height is {height:.2f}.")
输出结果为:My name is Charlie, I'm 30 years old, and my height is 185
标签:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)