随笔 - 97  文章 - 0  评论 - 1  阅读 - 44096

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

posted on   peijiao  阅读(114)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示