string.format 占位符 填充
时间: 2025-04-19 14:49:19 浏览: 32
### 使用 `string.format` 占位符进行字符串填充
在编程中,`string.format()` 方法提供了一种灵活的方式来格式化字符串。通过使用不同的占位符可以实现多种类型的变量插入到字符串模板中的效果。
#### 基本语法
基本的占位符由花括号 `{}` 表示,在调用 `.format()` 函数时按照参数顺序依次替换这些位置上的内容[^1]:
```python
formatted_string = "{} can be {}".format("Strings", "interpolated")
print(formatted_string)
```
#### 指定索引编号
也可以给每个花括号内的占位符指定一个数字来表示对应的参数序号,这允许重复利用同一个参数值而不需要多次传递相同的变量:
```python
greeting = "{0}, {1}! How's it going, {0}?".format("Hey", "there")
print(greeting)
```
#### 关键字命名方式
除了按位置外还可以采用关键字的形式传入参数名作为占位符的一部分,这种方式使得代码更具有可读性和自解释性:
```python
person_info = "My name is {name}. I am from {place}".format(name="Alice", place="Wonderland")
print(person_info)
```
#### 自动获取对象属性或列表元素
对于复杂的数据结构比如类实例或者序列类型可以直接访问其内部成员并用于格式化输出:
```python
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
someone = Person('Monty', 'Python')
presentation = '{p.first_name} {p.last_name}'.format(p=someone)
print(presentation)
numbers_list = ['One', 'Two']
number_output = '{} and {}'.format(*numbers_list)
print(number_output)
```
阅读全文
相关推荐


















