本人github
Python 3.6及以上版本支持格式化字符串,也称为f-字符串。这是一种在字符串中嵌入表达式的新方法。您只需要在字符串前面加上f
或F
,并在大括号{}
内写入表达式,Python会自动将其计算并转换为字符串。
基础用法
name = "Alice"
age = 30
# 使用f字符串
greeting = f"Hello, my name is {
name} and I am {
age} years old."
print(greeting)
输出:
Hello, my name is Alice and I am 30 years old.
表达式和函数
您还可以在大括号中使用表达式或调用函数:
x = 10
y = 20
result = f"The sum of {
x} and {
y} is {
x + y}."
print(result)
输出:
The sum of 10 and 20 is 30.
精度和格式
您还可以使用格式规范来控制值的显示方式:
pi = 3.141592653589793
formatted = f"Value of pi to 2 decimal places: {
pi:.2f}"
print(formatted)
输出:
Value of pi to 2 decimal places: 3.14
动态表达式
您甚至可以使用动态表达式:
item = "apple"
count = 5
message = f"There {
'is' if count == 1 else 'are'} {
count} {
item if count == 1 else item + 's'}."
print(message)
输出:
There are 5 apples.
f-字符串是一种非常强大和灵活的工具,可以让字符串格式化变得更加简单和直观。