格式化字符串
在这一步,你将学习 Python 中格式化字符串的现代且有效的方法。这对于通过将变量和表达式嵌入字符串中来创建动态且易读的输出来说至关重要。
虽然你可以使用 + 运算符来连接字符串,但在将字符串与非字符串类型(如数字)混合时,这种方式会变得笨拙,因为你必须使用 str() 手动进行转换。
Python 提供了更好的解决方案。最常见和推荐的方法是使用 f-strings(格式化字符串字面值)。
f-string 格式化
f-strings(格式化字符串字面值)在 Python 3.6 中引入,提供了一种简洁易读的方式,用于在字符串中嵌入表达式。你只需在字符串前加上 f 或 F 前缀,然后在花括号 {} 中写入表达式即可。
打开 string_formatting.py 文件,并添加以下代码:
## string_formatting.py
name = "Alice"
age = 30
## 使用 f-string 嵌入变量
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)
## 你也可以直接嵌入表达式
print(f"In 5 years, I will be {age + 5} years old.")
保存并运行脚本:
python ~/project/string_formatting.py
Hello, my name is Alice and I am 30 years old.
In 5 years, I will be 35 years old.
f-strings 还允许你使用格式说明符来控制嵌入值的格式,这些说明符跟在花括号内的冒号(:)后面。
将以下示例添加到 string_formatting.py 中:
## string_formatting.py
## ... (前面的代码) ...
pi = 3.14159265
## 将浮点数格式化为 2 位小数
print(f"The value of pi is approximately {pi:.2f}")
## 用前导零填充数字,总宽度为 8
order_id = 45
print(f"Order ID: {order_id:08}")
## 在给定空间内对齐文本(宽度为 10)
## < (左对齐), ^ (居中), > (右对齐)
text = "Python"
print(f"'{text:<10}'")
print(f"'{text:^10}'")
print(f"'{text:>10}'")
## 添加逗号作为千位分隔符
large_number = 1234567890
print(f"A large number: {large_number:,}")
保存并再次运行脚本:
python ~/project/string_formatting.py
Hello, my name is Alice and I am 30 years old.
In 5 years, I will be 35 years old.
The value of pi is approximately 3.14
Order ID: 00000045
'Python '
' Python '
' Python'
A large number: 1,234,567,890
在 f-strings 出现之前,str.format() 方法是格式化字符串的首选方式。它的工作原理是在字符串中放置占位符花括号 {},然后将值传递给 format() 方法。
将此示例添加到 string_formatting.py 的末尾:
## string_formatting.py
## ... (前面的代码) ...
## 使用 str.format() 方法
item = "moon"
cost = 99.95
statement = "The {} costs {:.2f} dollars.".format(item, cost)
print(statement)
保存并运行文件以查看输出:
python ~/project/string_formatting.py
Hello, my name is Alice and I am 30 years old.
In 5 years, I will be 35 years old.
The value of pi is approximately 3.14
Order ID: 00000045
'Python '
' Python '
' Python'
A large number: 1,234,567,890
The moon costs 99.95 dollars.
虽然 str.format() 仍然有用,但 f-strings 通常更具可读性且速度更快。