首页 › 问答 › Python › 正文 Python f-strings 怎么用?PEP 498 字面字符串插值语法详解? 2026-05-04 13:00:27 约 1 分钟读完 29 阅 文章导读 让我们来看一个 f-strings 的简单示例。 📋 目录 Ⅰ Python f-strings 示例 A A 博客文档招聘获取支持联系销售Python f-strings 示例 让我们来看一个 f-strings 的简单示例。 name = 'Pankaj' age = 34 f_string = f'My Name is {name} and my age is {age}' print(f_string) print(F'My Name is {name} and my age is {age}') # f 和 F 是相同的 name = 'David' age = 40 # f_string 已经被求值,不会再改变 print(f_string) 输出: My Name is Pankaj and my age is 34 My Name is Pankaj and my age is 34 My Name is Pankaj and my age is 34 Python 逐条执行语句,一旦 f-string 表达式被求值,即使表达式值发生变化,它们也不会改变。这就是为什么在上面的代码片段中,即使在程序后半部分 'name' 和 'age' 变量改变了,f_string 的值仍然保持不变。 1. 带有表达式和转换的 f-strings 我们可以使用 f-strings 将 datetime 转换为特定格式。我们还可以在 f-strings 中运行数学表达式。 from datetime import datetime name = 'David' age = 40 d = datetime.now() print(f'Age after five years will be {age+5}') # age = 40 print(f'Name with quotes = {name!r}') # name = David print(f'Default Formatted Date = {d}') print(f'Custom Formatted Date = {d:%m/%d/%Y}') 输出: Age after five years will be 45 Name with quotes = 'David' Default Formatted Date = 2018-10-10 11:47:12.818831 Custom Formatted Date = 10/10/2018 2. f-strings 支持 raw strings 我们也可以使用 f-strings 创建 raw strings。 print(f'Default Formatted Date:\n{d}') print(fr'Default Formatted Date:\n {d}') 输出: Default Formatted Date: 2018-10-10 11:47:12.818831 Default Formatted Date:\n 2018-10-10 11:47:12.818831 3. 带有对象和属性的 f-strings 我们也可以在 f-strings 中访问对象属性。 class Employee: id = 0 name = '' def __init__(self, i, n): self.id = i self.name = n def __str__(self): return f'E[id={self.id}, name={self.name}]' emp = Employee(10, 'Pankaj') print(emp) print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}') 输出: E[id=10, name=Pankaj] Employee: E[id=10, name=Pankaj] Name is Pankaj and id is 10 4. f-strings 调用函数 我们也可以在 f-strings 格式化中调用函数。 def add(x, y): return x + y print(f'Sum(10,20) = {add(10, 20)}') 输出: Sum(10,20) = 30 5. 带有空白字符的 f-string 如果表达式中有前导或尾随空白字符,它们会被忽略。如果字面字符串部分包含空白字符,则会保留。 >>> age = 4 * 20 >>> f' Age = { age } ' ' Age = 80 ' 6. 与 f-strings 一起使用的 lambda 表达式 我们也可以在 f-string 表达式中使用 lambda 表达式。 x = -20.45 print(f'Lambda Example: {(lambda x: abs(x)) (x)}') print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}') 输出: Lambda Example: 20.45 Lambda Square Example: 25 7. f-strings 杂项示例 让我们来看一些 Python f-strings 的杂项示例。 print(f'{"quoted string"}') print(f'{{ {4*10} }}') print(f'{{{4*10}}}') 输出: quoted string { 40 } {40} 这就是 Python 格式化字符串(又称 f-strings)的全部内容。 您可以从我们的 GitHub 仓库查看完整的 Python 脚本和更多 Python 示例。 参考:PEP-498,官方文档 感谢与 Community 一起学习。请查看我们的计算、存储、网络和管理数据库产品。 了解更多我们的产品Python String