1. f-string 主要概念

f-string 是 Python 3.6 中引入的一种新的字符串格式化方法,简化了字符串插值的过程,使得代码更简洁、更直观。f-string 的语法非常简单,就是在字符串前加上字母 fF,然后用花括号 {} 包裹变量或表达式。

2. 基本用法

f-string 让我们可以在字符串中直接插入 Python 表达式,Python 会自动将表达式的值转换为字符串并插入其中。

基本语法:

1
f"some text {expression} more text"
  • 示例 1:将变量插入字符串:
1
2
3
4
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# 输出: My name is Alice and I am 30 years old.
  • 示例 2:插入表达式(例如数学计算):
1
2
3
4
a = 5
b = 10
print(f"The sum of {a} and {b} is {a + b}.")
# 输出: The sum of 5 and 10 is 15.
  • 示例 3:格式化数值:
1
2
3
pi = 3.14159265
print(f"The value of pi is approximately {pi:.2f}.")
# 输出: The value of pi is approximately 3.14.

在这个例子中,{pi:.2f} 使用了格式化说明符,保留了 pi 的小数点后 2 位。

3. f-string 引入的来龙去脉

在 Python 3.6 之前,Python 提供了几种字符串格式化的方法:

  • 百分号 (%) 格式化:

    1
    2
    3
    name = "Alice"
    age = 30
    print("My name is %s and I am %d years old." % (name, age))
  • str.format() 方法:

    1
    2
    3
    name = "Alice"
    age = 30
    print("My name is {} and I am {} years old.".format(name, age))

这两种方法虽然在当时被广泛使用,但存在一些问题:

  • % 格式化 方法不够灵活且语法不够简洁,尤其是处理复杂表达式时。
  • str.format() 虽然功能更强大,但语法相对较长,尤其是在处理多个变量时,容易使代码显得冗长。

为了解决这些问题,Python 3.6 引入了 f-string,它的优势在于:

  • 更加简洁:直接在字符串中嵌入表达式。
  • 更加直观:在字符串中直接看到表达式的结果,减少了不必要的拼接操作。
  • 性能更优f-string 在运行时的性能比 str.format()% 格式化要好。

4. f-string 的高级用法

(1) 多行 f-string

你可以使用多行 f-string 来生成复杂的多行字符串。

1
2
3
4
5
6
7
8
9
name = "Alice"
age = 30
address = "123 Main St"
message = f"""
Name: {name}
Age: {age}
Address: {address}
"""
print(message)

(2) 条件表达式

你还可以在 f-string 中使用条件表达式(也称为三元表达式)。

1
2
3
age = 25
print(f"You are {'young' if age < 30 else 'old'}.")
# 输出: You are young.

(3) 嵌套 f-string

你可以在 f-string 中嵌套 f-string,让字符串格式化更加灵活。

1
2
3
4
name = "Alice"
age = 30
print(f"My name is {f'{name}'} and I am {f'{age}'} years old.")
# 输出: My name is Alice and I am 30 years old.

5. f-string 的局限性

虽然 f-string 提供了很多优点,但也有一些局限性:

  • 不能在 f-string 中嵌套未转义的 {}
  • f-string 中的表达式必须是有效的 Python 表达式,因此不能直接引用复杂的字符串或代码块。

总结

  • f-string 是 Python 3.6 引入的一种新的字符串格式化方法,语法简洁、直观,并且支持插入 Python 表达式、函数调用以及格式化数字和日期等。
  • 与旧的格式化方法(%str.format())相比,f-string 不仅提高了代码的可读性,也提升了性能。
  • f-string 是处理字符串插值的最佳选择,特别是在处理复杂字符串和频繁格式化时,它能显著提高代码效率和可维护性。