Python字符串格式化详解:%、str.format()、f-string与Template对比

Mia
Mia
发布时间:2026-10-13| 5人浏览过
原创

本文深入解析Python中四种字符串格式化方式:传统的%运算符、str.format()方法、Python 3.6引入的f-string以及Template类。通过对比各方法的语法特性、优缺点及适用场景,帮助开发者根据代码可读性、性能和维护需求选择最佳方案,特别推荐在Python 3.6+环境中优先使用f-string。

Python字符串格式化概述

提及Python的字符串格式化,大多数开发者首先想到的可能是使用百分号(%)运算符。然而,对于许多初学者而言,这往往是他们掌握的唯一一种格式化手段。

鉴于此,本文将首先回顾如何利用%运算符进行字符串格式化,并剖析其存在的局限性。随后,我们将详细介绍Python中另外三种高效且强大的格式化方案:str.format()、f-string以及模板字符串(Template),并针对不同的使用场景提供选择建议。

%运算符格式化字符串

一、%运算符格式化字符串

1. 基本用法

Python的字符串对象内置了通过%运算符进行格式化的功能,这是最基础的字符串格式化方式。例如:


In [11]: name = "Monty Python"
In [12]: "Hello, %s." % name
Out[12]: 'Hello, Monty Python.'

若需在字符串中插入多个变量,必须将这些变量封装在一个元组中,具体示例如下:


In [14]: name = "Monty Python"

In [15]: age = 100

In [16]: "Hello, %s. You are %d years old" % (name, age)
Out[16]: 'Hello, Monty Python. You are 100 years old'

2. 主要缺陷

尽管%运算符自Python诞生之初便已存在,且简单场景下代码直观易读,但当字符串内容复杂或变量数量增多时,其可读性会显著下降。例如在涉及多个变量的长字符串格式化时:


In [23]: first_name = "Eric"

In [24]: last_name = "Idle"

In [25]: age = 100

In [26]: profession = "comedian"

In [27]: affiliation = "Monty Python"

In [28]: "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
Out[28]: 'Hello, Eric Idle. You are 100. You are a comedian. You were a member of Monty Python.'

上述%格式化方式不仅代码冗长,还容易引发错误,主要原因在于该方式无法正确显示元组或字典等复杂数据结构。

Python官方文档对%运算符格式化方式持保留态度,明确指出:

  • The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).使用%格式化字符串会引发一系列异常,导致常见错误(例如无法正确显示元组和字典)。
  • Using the newerformatted string literals, the str.format() interface, ortemplate strings may help avoid these errors.
  • 官方建议使用更新的格式化字符串字面量(f-string)、str.format()接口或模板字符串(template strings)来避免上述错误。

Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility. 当然,这三种替代方案在简洁性、灵活性和可扩展性方面各有取舍。

str.format()格式化字符串

二、str.format()格式化字符串

1. 基本用法

str.format()是对%运算符格式化方式的改进,其语法结构类似于普通函数调用。

在str.format()中,待替换的占位符使用花括号{}表示:


In [29]: name = "Eric"

In [30]: age = 100

In [31]: "Hello, {}. You are {}.".format(name, age)
Out[31]: 'Hello, Eric. You are 100.'

此外,还可以通过索引指定format()参数中哪个变量对应哪个{}占位符,例如:


In [32]: name = "Eric"

In [33]: age = 100

In [34]: "Hello, {1}. You are {0}.".format(age, name)
Out[34]: 'Hello, Eric. You are 100.'

除了使用索引,还可以在{}中指定参数名称来实现相同功能,如:


In [36]: name = "Eric"

In [37]: age = 100

In [38]: "Hello, {name}. You are {age}.".format(age=age, name=name)
Out[38]: 'Hello, Eric. You are 100.'

基于上述方法,当待格式化的数据全部来自一个字典时,Python提供了更便捷的写法:


In [39]: person = {'name': 'Eric', 'age': 100}

In [40]: "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
Out[40]: 'Hello, Eric. You are 100.'

更进一步,利用字典拆包(**)可以进一步简化代码:


In [41]: person = {'name': 'Eric', 'age': 100}

In [42]: "Hello, {name}. You are {age}.".format(**person)
Out[42]: 'Hello, Eric. You are 100.'

2. 主要缺陷

虽然str.format()比%运算符更具可读性,但当变量数量增加时,生成的代码依然显得冗长:


In [43]: first_name = "Eric"

In [44]: last_name = "Idle"

In [45]: age = 74

In [46]: profession = "comedian"

In [47]: affiliation = "Monty Python"

In [48]: print(("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格式化字符串

f-string在Python 3.6中引入(详见PEP 498),全称为格式化字符串字面量(formatted string literals)。

f-string是一种以字母f开头的字符串字面量,花括号{}内包含变量或表达式。这些变量或表达式将在运行时通过__format__协议被替换为具体值。

1. 基本用法

简单的f-string格式化示例如下:


In [49]: name = "Eric"

In [50]: age = 100

In [51]: f"Hello, {name}. You are {age}."
Out[51]: 'Hello, Eric. You are 100.'

如前所述,{}中不仅可以接受变量,还可以直接接受表达式,例如:


In [52]: f"{2 * 37}"
Out[52]: '74'

f-string的强大之处在于,{}中还可以接受函数调用:


In [53]: def to_lowercase(input):
  ...:   return input.lower()
  ...: 

In [54]: name = "Eric Idle"

In [55]: f"{to_lowercase(name)} is funny."
Out[55]: 'eric idle is funny.'

甚至可以直接对自定义类的对象使用f-string,示例如下:


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}."

  def __repr__(self):
    return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"


def main():
  new_comedian = Comedian("Eric", "Idle", "74")
  print(f"{new_comedian}")


if __name__ == '__main__':
  main()

上述代码的执行结果为:

Eric Idle is 74.

Template类格式化字符串

四、Template类格式化字符串

https://www.jb51.net/article/155119.htm

五、参考资料

[1] Python 3's f-Strings: An Improved String Formatting Syntax (Guide) [2] Python String Formatting Best Practices

本文介绍了Python中格式化字符串的四种实现方式。如需了解更多Python格式化字符串相关内容,建议查阅本站过往文章或继续浏览后续文章。感谢大家的支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。