f-string 是 Python 中一种用于格式化字符串的强大工具,它允许你在字符串中插入变量、表达式以及其他值。你可以使用大括号 {}
来标识要插入的变量或表达式,并在字符串前添加一个 f
或 F
前缀来指示这是一个 f-string。以下是一些 f-string 的用法示例:
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.
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
print(result)
# 输出: The sum of 5 and 10 is 15.
price = 19.99
formatted_price = f"Price: ${price:.2f}"
print(formatted_price)
# 输出: Price: $19.99
在上面的示例中,{price:.2f}
表示将 price
变量格式化为带有两位小数的浮点数。
person = {"name": "Bob", "age": 25}
fruits = ["apple", "banana", "cherry"]
message = f"{person['name']} is {person['age']} years old and likes {fruits[0]}."
print(message)
# 输出: Bob is 25 years old and likes apple.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# 输出: Hello, Alice!
这些示例展示了 f-string 的多种用法,它们使字符串格式化变得更加简单和直观。你可以在字符串中插入变量、表达式、字典键、列表元素,甚至调用函数,以满足不同的字符串格式化需求。