在Python中,`format()`函数用于格式化字符串输出,它允许你控制输出的格式,包括小数位数、对齐方式、宽度、填充字符以及日期和时间的格式化。下面是一些使用`format()`函数进行格式化输出的例子:
控制小数位数
```python
num = 3.
print("{:.2f}".format(num)) 输出:3.14
控制字符串的对齐方式
```python
name = "Alice"
print("{:10}".format(name)) 右对齐输出
print("{:^10}".format(name)) 居中输出
控制输出的宽度
```python
num = 42
print("{:5d}".format(num)) 输出宽度为5
控制输出的填充字符
```python
num = 42
print("{:0>5d}".format(num)) 输出宽度为5,左侧填充0
格式化输出日期和时间
```python
from datetime import datetime
now = datetime.now()
print("{:%Y-%m-%d %H:%M:%S}".format(now)) 输出当前日期和时间
格式化指示符
```python
print("{:,.2f}".format(1.)) 输出:1.14
print("{:10.2f}".format(1.)) 输出宽度为10,保留2位小数
格式化输出带关键字的字符串
```python
print("{a} {b} {a}".format(a="hello", b="world")) 输出:hello world hello
格式化输出带索引的字符串
```python
print("{0} {1} {0}".format("hello", "world")) 输出:hello world hello
格式化输出带多个参数的字符串
```python
print("{0} {1} {2}".format("hello", "world", "python")) 输出:hello world python
格式化输出带多个关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置参数的字符串
```python
print("{0} {1} {2}".format("hello", "world", "python")) 输出:hello world python
格式化输出带多个关键字位置参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串
```python
print("{a} {b} {c}".format(a="hello", b="world", c="python")) 输出:hello world python
格式化输出带多个位置关键字参数的字符串