`format` 是 Python 中的一个字符串格式化函数,用于将变量或表达式插入到字符串中,并控制它们在字符串中的显示方式。`format` 函数的基本语法是使用花括号 `{}` 作为占位符,并在其中使用冒号 `:` 来指定格式说明符。
1. 替换占位符:
```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.`
2. 指定参数位置:
```python
print("{1} {0} {1}".format("Alice", "Bob"))
输出:`Bob Alice Bob`
3. 格式化数字:
```python
pi = 3.
print("The value of pi is approximately {:.2f}".format(pi))
输出:`The value of pi is approximately 3.14`
`format` 函数非常灵活,可以处理不同类型的数据,并且可以指定小数点后的位数、对齐方式等。它还支持命名参数,使得格式化字符串更加直观和易于维护。