formatter使用
时间: 2023-07-11 22:08:00 浏览: 52
在 Python 中,我们可以使用 `formatter` 对字符串进行格式化。`formatter` 可以帮助我们将变量的值插入到字符串中。
下面是一个简单的例子:
```python
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
```
输出结果为:
```
My name is Alice and I am 25 years old.
```
在这个例子中,我们使用了 `{}` 占位符来表示需要插入变量的位置。我们使用 `format()` 方法来指定需要插入的变量的值。
我们还可以使用 `{}` 中的数字来指定变量的顺序。例如:
```python
name = "Alice"
age = 25
print("My name is {0} and I am {1} years old. {0} is my favorite name.".format(name, age))
```
输出结果为:
```
My name is Alice and I am 25 years old. Alice is my favorite name.
```
在这个例子中,我们使用了 `{0}` 和 `{1}` 来指定变量的顺序。我们也可以使用变量名来指定变量的值,例如:
```python
name = "Alice"
age = 25
print("My name is {name} and I am {age} years old. {name} is my favorite name.".format(name=name, age=age))
```
输出结果为:
```
My name is Alice and I am 25 years old. Alice is my favorite name.
```
在这个例子中,我们使用了变量名来指定变量的值。注意,在 `format()` 方法中,我们需要使用 `key=value` 的形式来指定变量的值。
除了使用 `{}` 占位符外,我们还可以使用 `%` 占位符来格式化字符串。例如:
```python
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
```
输出结果为:
```
My name is Alice and I am 25 years old.
```
在这个例子中,我们使用 `%s` 来表示字符串类型的变量,使用 `%d` 来表示整数类型的变量。我们使用 `%` 运算符来将变量的值插入到字符串中。需要注意的是,使用 `%` 占位符时,需要将所有的变量值都放在一个元组中。