pythonformat用法
时间: 2025-06-21 15:55:14 浏览: 7
### Python 中 `format` 方法的用法详解
Python 的字符串格式化功能非常强大,可以灵活地将变量嵌入到字符串中。以下是对 `format` 方法的详细解析:
#### 1. 基本用法:通过位置填充
`format` 方法支持通过位置索引来填充字符串中的占位符 `{}`。例如:
```python
print('hello {0} i am {1}'.format('world', 'python')) # 输出: hello world i am python
print('hello {} i am {}'.format('world', 'python')) # 输出: hello world i am python
```
上述代码展示了如何通过位置参数自动填充占位符[^1]。
还可以重复使用同一个位置参数:
```python
print('hello {0} i am {1}. a new language-- {1}'.format('world', 'python'))
# 输出: hello world i am python. a new language-- python
```
#### 2. 使用解包操作填充
在 `format` 方法中,可以结合解包操作符 `*` 和 `**` 来填充列表、元组或字典中的值。
- **列表/元组解包**:
```python
foods = ['fish', 'beef', 'fruit']
s = 'i like eat {} and {} and {}'.format(*foods)
print(s) # 输出: i like eat fish and beef and fruit
s = 'i like eat {2} and {0} and {1}'.format(*foods)
print(s) # 输出: i like eat fruit and fish and beef
```
这里通过 `*` 解包了列表 `foods` 的元素,并按照指定顺序填充到占位符中[^2]。
- **字典解包**:
```python
dict_temp = {'name': 'Lily', 'age': 18}
s = 'My name is {name}, i am {age} years old'.format(**dict_temp)
print(s) # 输出: My name is Lily, i am 18 years old
```
字典需要通过 `**` 进行解包,并且字典中的键名必须与占位符中的名称一致。
#### 3. 自定义占位符顺序
可以通过显式指定占位符的位置来控制输出顺序:
```python
print('{0},{1},{2}'.format('a', 'b', 'c')) # 输出: a,b,c
print('{2},{1},{0}'.format('a', 'b', 'c')) # 输出: c,b,a
print('{2},{1},{0}'.format(*'abc')) # 输出: c,b,a
print('{0}{1}{0}'.format('aa', 'bb')) # 输出: aabbaa
```
上述代码展示了如何通过调整占位符的索引来自定义输出顺序[^3]。
#### 4. 格式化数字
`format` 方法还支持对数字进行格式化:
```python
# 浮点数格式化
print('The value is {:.2f}'.format(3.14159)) # 输出: The value is 3.14
# 整数格式化
print('The value is {:d}'.format(123)) # 输出: The value is 123
# 科学计数法
print('The value is {:.2e}'.format(123456789))
# 输出: The value is 1.23e+08
```
#### 5. 对齐和宽度控制
可以使用 `:<`、`:>`、`:^` 来控制对齐方式,以及指定字段宽度:
```python
print('|{:<10}|'.format('left')) # 左对齐,总宽度为10
# 输出: |left |
print('|{:>10}|'.format('right')) # 右对齐,总宽度为10
# 输出: | right|
print('|{:^10}|'.format('center')) # 居中对齐,总宽度为10
# 输出: | center |
```
#### 6. 填充字符
除了默认的空格填充外,还可以指定其他字符作为填充:
```python
print('|{:=^10}|'.format('center')) # 使用等号填充并居中
# 输出: |==center==|
```
### 总结
`format` 方法是 Python 中一种强大的字符串格式化工具,支持通过位置、关键字、解包等方式填充占位符,并能够对数字、对齐方式等进行精确控制[^1][^2][^3]。
阅读全文
相关推荐















