Python3 字符串格式化:%、str.format() 与 f-string 对比详解
本文深入解析 Python3 中三种字符串格式化方式:传统的 % 操作符、改进的 str.format() 方法以及 Python 3.6 引入的 f-string。通过具体代码示例对比它们在处理多变量、字典解包及表达式嵌入时的语法差异与性能表现,重点阐述 f-string 在代码可读性和执行效率上的优势,帮助开发者选择最适合的格式化方案。
Python 字符串格式化概述
在 Python 开发中,字符串格式化是将变量嵌入文本的常见需求。了解不同版本的实现机制对于编写清晰高效的代码至关重要。
% 操作符及其局限性
% 操作符是 Python 早期版本中主要的字符串格式化方式,其语法类似于 C 语言的 printf。
以下是 % 操作符的基础使用示例:
>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'
当字符串中包含多个需要插入的变量时,% 操作符通过元组传递这些值。
>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello, Eric. You are 74.'
然而,随着需要替换的变量数量增加,使用 % 操作符会导致代码结构变得混乱且难以阅读,特别是在处理大量参数时。
>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'
str.format() 方法详解
str.format() 方法是 Python 对 % 格式化方式的改进,旨在提供更直观和灵活的字符串拼接体验。
str.format() 借鉴了常规函数调用的语法,允许开发者通过定义对象的 __format__() 方法来精确控制格式化行为。
str.format() 的基本使用方式如下:
>>> name = "Eric"
>>> age = 74
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'
相较于 % 操作符,str.format() 提供了更高的灵活性,例如支持通过数字索引来指定变量在字符串中的位置。
>>> name = "Eric"
>>> age = 74
>>> "Hello, {1}. You are {0}.".format(age, name)
'Hello, Eric. You are 74.'
为了提升代码的可读性,可以在大括号 {} 中使用具有语义意义的参数名称。
>>> name = "Eric"
>>> age = 74
>>> "Hello, {name}. You are {age}".format(name=name, age=age)
'Hello, Eric. You are 74'
对于字典类型的数据,可以通过键名直接访问其值进行格式化。
>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
'Hello, Eric. You are 74.'
或者使用更简洁的字典解包语法 ** 来传递参数。
>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(**person)
'Hello, Eric. You are 74.'
尽管 str.format() 比 % 操作符有所改进,但当需要替换的变量非常多时,该方法生成的代码依然显得冗长且不易维护。
>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, {first_name} {last_name}. You are {age}. \
You are a {profession}. You were a member of {affiliation}."\
.format(first_name=first_name, last_name=last_name, age=age, \
profession=profession, affiliation=affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'
f-string 的优势与应用
f-string(formatted string literals)是 Python 3.6 引入的一种更现代、更简洁的字符串格式化方式。
f-string 的基本用法是在字符串前加上字母 f 或 F,并在字符串内部使用大括号 {} 包裹变量名。
>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'
f-string 的强大之处在于可以直接在 {} 中嵌入表达式,而不仅仅是变量名。
>>> f"{2 * 37}"
'74'
>>> def to_lowercase(input):
... return input.lower()
>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny"
'eric idle is funny'
>>> f"{name.lower()} is funny"
'eric idle is funny'
此外,f-string 支持直接嵌入对象实例,前提是该对象实现了 __str__ 或 __repr__ 方法。
class Comedian:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def __str__(self):
return f"{self.first_name} {self.last_name} is {self.age}"
new_comedian = Comedian("Eric", "Idle", 74)
print(f"{new_comedian}")
# Eric Idle is 74
多行 f-string
>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
... f"Hi {name}. "
... f"You are a {profession}. "
... f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'
总结与建议
综上所述,Python3 提供了多种字符串格式化选项。% 操作符历史悠久但灵活性有限;str.format() 增强了功能但语法稍显繁琐;f-string 则在可读性、性能和简洁性上达到了最佳平衡,推荐在现代 Python 项目中优先使用。
希望本文对理解 Python3 字符串格式化语法有所帮助。如有任何疑问,欢迎留言交流,我们将及时回复。感谢大家的支持! 如果您觉得本文有价值,欢迎转载,请注明出处,谢谢!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













