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 官方文档。