当前位置:首页>维修大全>综合>

format方法的格式控制实例(format格式化方法如何使用)

format方法的格式控制实例(format格式化方法如何使用)

更新时间:2025-05-28 21:30:36

format方法的格式控制实例

下面是一些使用Python中`format()`方法进行格式控制的实例:

1. 格式化整数:

```python

num = 42

print("The number is: {:d}".format(num)) # 输出: The number is: 42

```

2. 格式化浮点数:

```python

pi = 3.1415926

print("The value of pi is: {:.2f}".format(pi)) # 输出: The value of pi is: 3.14

```

3. 格式化字符串:

```python

name = "Alice"

age = 25

print("My name is {0} and I am {1} years old.".format(name, age)) # 输出: My name is Alice and I am 25 years old.

```

4. 对齐和填充:

```python

text = "Hello"

print("{:>10}".format(text)) # 输出: Hello (右对齐,总宽度为10)

print("{:<10}".format(text)) # 输出: Hello (左对齐,总宽度为10)

print("{:^10}".format(text)) # 输出: Hello (居中对齐,总宽度为10)

print("{:_<10}".format(text)) # 输出: Hello____ (使用下划线进行填充)

```

5. 格式化日期和时间:

```python

from datetime import datetime

now = datetime.now()

print("Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now)) # 输出: Current date and time: 2022-01-01 12:34:56

```

这些只是格式控制的一些示例,`format()`方法提供了丰富的格式化选项和功能,可以根据需要进行更复杂的格式化操作。您可以参考Python官方文档中关于`format()`方法的更多信息,以了解更多格式化选

Format ( my name is %6s.[' wind ]);返回后就是 my name is wind。

更多栏目