format
函數可以通過以下方式調用:
{}
占位符,然后調用 format
函數將需要填充的值傳遞進去,示例如下:name = "Alice"
age = 25
print("My name is {}, and I am {} years old.".format(name, age))
輸出結果為:My name is Alice, and I am 25 years old.
name = "Bob"
age = 30
print("My name is {0}, and I am {1} years old.".format(name, age))
輸出結果為:My name is Bob, and I am 30 years old.
name = "Charlie"
age = 35
print("My name is {n}, and I am {a} years old.".format(n=name, a=age))
輸出結果為:My name is Charlie, and I am 35 years old.
此外,format
函數還可以用于格式化數字、日期等特定類型的值,具體用法可以參考 Python 官方文檔。