format()方法是用于格式化字符串的内置方法,它允许我们在字符串中插入变量,以及对变量进行格式化输出。
基本用法如下:
示例代码如下所示:
name = "Alice"
age = 30
txt = "My name is {} and I am {} years old."
formatted_txt = txt.format(name, age)
print(formatted_txt)
输出:
My name is Alice and I am 30 years old.