`format` 是 Python 中用于字符串格式化的函数。它允许你在字符串中插入变量或表达式,并控制它们的显示格式。`format` 函数的基本语法是使用花括号 `{}` 作为占位符,并通过冒号 `:` 和其他格式代码指定格式化方式。
```python
基本用法
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
输出:My name is Alice and I am 30 years old.
指定位置
print("The {0} is at position {1}.".format("apple", 2))
输出:The apple is at position 2.
指定格式
print("The price is ${0:.2f}.".format(123.456))
输出:The price is $123.46.
`format` 函数非常灵活,可以处理不同类型的数据,并且可以自定义格式化选项,比如整数、浮点数、小数位数保留和百分比等。