f-string是Python中格式化字符串的一种方式,它的语法为在字符串前面加上小写字母"f",然后在字符串中使用大括号{}来包含想要格式化的变量或表达式。下面是一些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.a = 10
b = 20
print(f"The sum of {a} and {b} is {a + b}.")输出:
The sum of 10 and 20 is 30.x = 3.1415926535
print(f"The value of pi is approximately {x:.3f}.")输出:
The value of pi is approximately 3.142.name = "Alice"
age = 30
print(f"My name is {name.upper()} and I am {age} years old.
{{This is a curly brace}}")输出:
My name is ALICE and I am 30 years old.
{This is a curly brace}