当我们使用 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 = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}.")
# 输出: The sum of 10 and 20 is 30.
其他规则:
- 格式化输出:
可以在大括号内部使用格式说明符指定输出的格式,例如,控制浮点数的小数位数或宽度等。
pi = 3.141592653589793
print(f"Pi is approximately {pi:.2f}.")
# 输出: Pi is approximately 3.14.
- 调用函数:
可以在 f-string 中调用函数来进行字符串拼接或格式化。
def greet(name):
return f"Hello, {name}!"
print(greet("Bob"))
# 输出: Hello, Bob!
- 转义字符:
可以在 f-string 中使用转义字符,如 \n 表示换行符。
print(f"First line.\nSecond line.")
# 输出:
# First line.
# Second line.
- 字面大括号:
如果要输出字面上的大括号 {},需要使用两对大括号来进行转义。
print(f"{{}}")
# 输出: {}
这些规则根据需要进行格式化输出、调用函数等操作。