Python中的`format`方法是一种强大的字符串格式化工具,它允许你以灵活的方式将变量插入到字符串中。以下是`format`方法的基本用法:
基本格式
```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.
指定顺序
```python
print("My name is {0} and I am {1} years old.".format(name, age))
输出:
```
My name is Alice and I am 25 years old.
命名参数
```python
print("My name is {name} and I am {age} years old.".format(name=name, age=age))
输出:
```
My name is Alice and I am 25 years old.
格式化数字
```python
pi = 3.
print("The value of pi is {:.2f}.".format(pi))
输出:
```
The value of pi is 3.14.
类型转换
```python
print("Chen xin is a cute {!s}.".format("baby"))
输出:
```
Chen xin is a cute baby.
右对齐、中间对齐、取位数
```python
print("Right align: {:<10} | Center align: {:^10} | Precision: {:.2f}".format("123", "456", 789.12345))
输出:
```
Right align: 123| Center align: 456| Precision: 789.12
连接字符串
```python
print("Python version is {}.".format("3.6.5"))
输出:
```
Python version is 3.6.5.
指定顺序连接
```python
print("Silly girl's name is {}.".format("Silly"))
输出:
```
Silly girl's name is Silly.
指定参数连接
```python
print("Silly is {} years old and loves to {}.".format(24, "stare"))
输出:
```
Silly is 24 years old and loves to stare.
`format`方法的使用非常灵活,可以根据需要选择不同的格式化选项。希望这些示例能帮助你理解`format`方法在Python中的应用