python()\t.format
时间: 2025-06-21 17:30:15 浏览: 4
### Python `format()` 方法使用说明
`format()` 是 Python 中用于字符串格式化的强大工具之一。它允许通过指定占位符来控制变量的显示方式,从而实现灵活的字符串拼接和数据展示。
#### 基本语法
`str.format(*args, **kwargs)`
其中 `*args` 表示位置参数,而 `**kwargs` 则表示关键字参数。可以通过花括号 `{}` 来定义占位符的位置以及其对应的值[^2]。
#### 占位符结构
占位符的一般形式如下:
```
{field_name:conversion_flags}
```
- `field_name`: 可以是一个整数(代表按顺序传递给 `.format()` 的参数索引),也可以是字符串键名。
- `conversion_flags`: 定义如何转换字段的内容,比如宽度、精度、对齐方式等。
---
#### 示例代码
以下是几个常见的用法:
1. **基本替换**
```python
name = "Alice"
age = 30
greeting = "Name: {}, Age: {}".format(name, age)
print(greeting) # 输出:Name: Alice, Age: 30
```
2. **命名参数**
```python
data = {"first": "John", "last": "Doe"}
full_name = "{first} {last}".format(**data)
print(full_name) # 输出:John Doe
```
3. **数值格式化**
- 浮点数保留两位小数:
```python
pi = 3.141592653589793
formatted_pi = "PI is approximately {:.2f}".format(pi)
print(formatted_pi) # 输出:PI is approximately 3.14
```
- 科学计数法表示浮点数:
```python
large_number = 123456789.0
scientific_notation = "{:.2e}".format(large_number)
print(scientific_notation) # 输出:1.23e+08
```
4. **日期时间格式化**
如果尝试将浮点型对象作为日期处理,则会抛出错误提示未知格式码 `'d'` 对于类型为 `'float'` 的对象。因此需注意输入类型的匹配性。
5. **填充与对齐**
支持多种字符填充及方向调整操作:
```python
text = "hello"
padded_text = "|{:>10}|".format(text) # 右对齐
centered_text = "|{:^10}|".format(text) # 居中
filled_text = "|{:-<10}|".format(text) # 左对齐并填充减号
print(padded_text) # 输出:| hello|
print(centered_text) # 输出:| hello |
print(filled_text) # 输出:|hello-----|
```
---
#### 错误案例分析
当遇到类似 `"ValueError: Unknown format code 'd'"` 这样的异常时,通常是因为试图应用不支持的时间/数字格式到非兼容的数据类型上所致。例如下面的例子展示了不当使用的场景及其修正方案:
```python
value = 123.456
try:
invalid_format = "{:d}".format(value) # 尝试把 float 当作 int 处理引发 ValueError
except Exception as e:
print(e)
correct_usage = "{:g}".format(int(value)) # 转换后再格式化即可正常工作
print(correct_usage) # 输出:123
```
---
### 总结
以上介绍了 Python 中 `format()` 函数的基础概念、典型应用场景以及一些常见陷阱规避技巧。掌握这些知识点有助于编写更加清晰易读且功能强大的程序逻辑。
阅读全文
相关推荐
















