Python 提供了多种字符串格式化的方法,下面我将详细介绍各种方式及其用法。
1. % 格式化 (传统方法)
这是从 C 语言继承的格式化方法:
# 基本用法
name = "Alice"
age = 25
print("Hello, %s! You are %d years old." % (name, age))
# 输出: Hello, Alice! You are 25 years old.
# 常用格式符:
# %s - 字符串
# %d - 十进制整数
# %f - 浮点数
# %x - 十六进制整数
# 宽度和精度控制
pi = 3.14159
print("Pi: %8.2f" % pi) # 总宽度8,保留2位小数
# 输出: Pi: 3.142. str.format() 方法 (Python 2.6+)
更灵活强大的格式化方法:
# 位置参数
print("Hello, {}! You are {} years old.".format("Alice", 25))
# 输出: Hello, Alice! You are 25 years old.
# 索引参数
print("Hello, {0}! {1} is {0}'s friend.".format("Alice", "Bob"))
# 输出: Hello, Alice! Bob is Alice's friend.
# 关键字参数
print("Hello, {name}! You are {age} years old.".format(name="Alice", age=25))
# 格式化数字
pi = 3.14159
print("Pi: {:.2f}".format(pi)) # 保留2位小数
print("Pi: {:8.2f}".format(pi)) # 宽度8,保留2位小数
print("Number: {:05d}".format(42)) # 宽度5,前面补0
# 千位分隔符
print("Large number: {:,}".format(1000000))
# 输出: Large number: 1,000,000
# 百分比
print("Success rate: {:.1%}".format(0.856))
# 输出: Success rate: 85.6%3. f-string (Python 3.6+)
最现代、最简洁的格式化方法:
name = "Alice"
age = 25
# 基本用法
print(f"Hello, {name}! You are {age} years old.")
# 表达式计算
a, b = 5, 3
print(f"{a} + {b} = {a + b}")
# 输出: 5 + 3 = 8
# 调用函数
def get_greeting():
return "Hello"
print(f"{get_greeting()}, {name}!")
# 格式化数字
pi = 3.14159
print(f"Pi: {pi:.2f}") # 保留2位小数
print(f"Pi: {pi:8.2f}") # 宽度8,保留2位小数
print(f"Number: {42:05d}") # 宽度5,前面补0
# 对齐
text = "Python"
print(f"|{text:<10}|") # 左对齐,宽度10
print(f"|{text:>10}|") # 右对齐,宽度10
print(f"|{text:^10}|") # 居中对齐,宽度10
# 千位分隔符和百分比
large_number = 1000000
rate = 0.856
print(f"Large number: {large_number:,}")
print(f"Success rate: {rate:.1%}")
# 字典和对象访问
person = {"name": "Alice", "age": 25}
print(f"Name: {person['name']}, Age: {person['age']}")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Bob", 30)
print(f"Name: {p.name}, Age: {p.age}")4. 模板字符串 (Template Strings)
适合用户提供的模板:
python
from string import Template
template = Template("Hello, $name! You are $age years old.")
result = template.substitute(name="Alice", age=25)
print(result)
# 输出: Hello, Alice! You are 25 years old.
# 安全替换,如果缺少参数不会报错
safe_result = template.safe_substitute(name="Alice")
print(safe_result)
# 输出: Hello, Alice! You are $age years old.5. 格式化对比
name = "Alice"
age = 25
score = 95.5
# 四种方式对比
print("%s is %d years old, score: %.1f" % (name, age, score))
print("{} is {} years old, score: {:.1f}".format(name, age, score))
print("{name} is {age} years old, score: {score:.1f}".format(name=name, age=age, score=score))
print(f"{name} is {age} years old, score: {score:.1f}")
# 所有输出: Alice is 25 years old, score: 95.5总结
% 格式化: 传统方法,适合简单场景
str.format(): 功能强大,兼容性好
f-string: 最现代、最简洁,性能最好(推荐使用)
模板字符串: 适合用户提供的模板,安全性高
对于新项目,强烈推荐使用 f-string,它语法简洁、性能优越且易于阅读。
评论