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 2023-05-20 17:24  peijiao  阅读(131)  评论(0)    收藏  举报