Python中的`format`函数是一种强大的字符串格式化工具,它允许你在字符串中插入变量的值,并且支持多种格式化选项,如对齐、填充和指定数据类型等。以下是`format`函数的基本用法和一些进阶技巧:
基本用法
占位符替换
使用大括号`{}`作为占位符,并通过`format`方法传入要替换的值。
```python
name = "小明"
age = 18
print("大家好,我叫{},今年{}岁。".format(name, age))
输出: 大家好,我叫小明,今年18岁。
```
位置参数
通过在占位符中指定参数的顺序来插入值。
```python
name = "Alice"
age = 30
print("My name is {}, I'm {} years old.".format(name, age))
输出: My name is Alice, I'm 30 years old.
```
关键字参数
通过指定参数名来插入值,这使得代码更易读。
```python
name = "Bob"
age = 25
print("My name is {name}, I'm {age} years old.".format(name=name, age=age))
输出: My name is Bob, I'm 25 years old.
```
进阶技巧
指定数据类型
可以使用不同的格式说明符来指定变量的数据类型,如浮点数、整数、字符串等。
```python
pi = 3.141592653589793
print("{:.2f}".format(pi)) 输出: 3.14
```
对齐和填充
可以使用`:`后跟一个或多个格式说明符来控制对齐和填充。
```python
print("{:10}".format("hello")) 输出: hello ,右对齐,总宽度为10
print("{:<10}".format("hello")) 输出: hello ,左对齐,总宽度为10
print("{:^10}".format("hello")) 输出: hello ,居中对齐,总宽度为10
```
字段宽度
可以指定每个字段的最小宽度,如果字段内容不足,则会在左侧用空格填充。
```python
print("{:10} is {:5} years old.".format(name, age)) 左对齐,宽度为10和5
print("{:>10} is {:>5} years old.".format(name, age)) 右对齐
```
科学计数法
可以使用`e`格式说明符来以科学计数法表示数字。
```python
print("{:e}".format(1000000)) 输出: 1.000000e+06
```
命名空间访问
可以使用字典来存储键值对,并通过名称访问这些值。
```python
person = {"name": "张三", "age": 25}
print("姓名:{p[name]},年龄:{p[age]}".format(p=person))
输出: 姓名:张三,年龄:25
```
实战案例
动态生成表格
可以使用`format`函数动态生成表格数据。
```python
headers = ["Name", "Age", "City"]
data = [
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 22, "Chicago"]
]
table = "\n".join(["|".join([f"{row[i]:{10}}" for i in range(len(row))]) for row in data])
print(table)
```
日志格式化
可以使用`format`函数来格式化日志信息,使其更易读。
```python
log_entry = "Error: {0} in {1} at line {2}".format(message, file, line_number)
print(log_entry)
```
通过这些基本用法和进阶技巧,`format`函数可以灵活地应用于各种字符串格式化需求,提高代码的可