Python f-string

Python f-string(格式化字符串字面量)允许您通过将变量或表达式放在花括号 {} 中来将其直接插入字符串。

这种方法使您的代码更具可读性,并且通常比其他字符串格式化技术更快。

示例

name = "Jennifer"
age = 23

# Use f-string to embed the name and age variables in a string message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Jennifer and I am 23 years old.

Python f-string 语法

f-string 以 fF 开头,后跟引号。将您想嵌入的任何变量或表达式放在字符串内的花括号 {} 中。

例如,

f"string with {expression}"

这里,

  • fF:在字符串前加上 fF 以将其指定为 f-string。
  • " ":在字符串周围使用双引号或单引号。
  • {expression}:将任何变量、计算或表达式放在花括号 {} 内,以将其嵌入字符串中。

示例:Python f-string

language = "Python"

# Use f-string to embed the language variable in a string
text = f"Learn {language} with 'ProgramizPRO'."

print(text)

输出

Learn Python with 'ProgramizPRO'.

在上面的例子中:

  • f"Learn {language} with 'ProgramizPRO'." 是 f-string。
  • {language}language 变量的占位符。

在 f-string 中评估表达式

您可以直接在 f-string 中进行计算。例如,

num1 = 5
num2 = 4

# Evaluate the sum of num1 and num2 inside f-string result = f"Sum of {num1} and {num2} is {num1 + num2}."
print(result)

输出

Sum of 5 and 4 is 9.

在这里,{num1 + num2} 是在 f-string 中计算的表达式。


Python f-string 占位符

您可以在 f-string 的占位符中放置各种表达式。例如,

在占位符中调用函数

您可以直接在 f-string 占位符中调用函数,返回值将嵌入字符串中。

def greeting():
    return "Good morning"

# Call greeting() inside f-string text = f"{greeting()}, everyone!"
print(text) # Output: Good morning, everyone!

在此,函数 greeting() 返回 "Good morning",然后通过 {greeting()} 直接放入 f-string 中。

在占位符中使用条件表达式

您可以在 f-string 占位符中使用条件(if-else)表达式,以根据变量值动态调整输出。

age = 18

# Using a conditional expression inside the f-string text = f"You are {'an adult' if age >= 18 else 'a minor'}."
print(text) # Output: You are an adult.

在此示例中

  • { 'an adult' if age >= 18 else 'a minor' } 评估条件。
  • 如果 age18 或更大,它将输出 "an adult";否则,它将输出 "a minor"

在占位符中访问字典值

您还可以通过在花括号 {} 中使用字典键来直接在 f-string 中访问字典值。

person = {"country": "USA", "employee_ID": 121}

# Accessing dictionary values inside the f-string text = f"Country: {person['country']}, Employee ID: {person['employee_ID']}"
print(text) # Output: Country: USA, Employee ID: 121

在上面的示例中,我们在 f-string 中访问了 person 字典的值。

这里,

  • {person['country']} 是一个访问 country 键值的占位符。
  • {person['employee_ID']} 是一个访问 employee_ID 键值的占位符。

使用 f-strings 的技巧

如何在 f-string 中处理引号?

如果 f-string 使用双引号,请在其中使用单引号,反之亦然。否则,它会引发语法错误。即,

有效方式

# Double quotes outside, single quotes inside
text = f"Learn {language} with 'ProgramizPRO'." 

# Single quotes outside, double quotes inside
text = f'Learn {language} with "ProgramizPRO".'  

无效方式

# Causes a syntax error due to matching quotes inside and outside
text = f'Learn {language} with 'ProgramizPRO'.'
text = f"Learn {language} with "ProgramizPRO"."
为什么使用 f-strings?

以下是 f-strings 被广泛使用的一些原因

可读性强:f-strings 通过直接将变量嵌入字符串中,使代码更简洁、更具可读性。

速度快:它们比 .format() 等旧方法更快,因为它们是在运行时进行评估的。

灵活性高:f-strings 允许在字符串中使用表达式和函数调用。

总之,f-strings 是一种快速、可读且通用的字符串格式化方法。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战