format()方法是用于格式化字符串的內(nèi)置方法,它允許我們在字符串中插入變量,以及對變量進行格式化輸出。
基本用法如下:
示例代碼如下所示:
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.