#format函数
在Python中,`format`函数是一个非常实用的函数,用于格式化字符串,它可以使用占位符将值插入字符串中,并且可以使用各种选项来控制格式化的方式,下面是一个详细的介绍:
## 1. 基本用法
`format`函数用于将值插入字符串中,它使用大括号`{}`作为占位符,然后将要插入的值传递给`format`函数。
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
在这个例子中,`{}`是占位符,`name`和`age`是要插入的值,通过传递这些值给`format`函数,它们被插入到字符串中相应的位置。
## 2. 格式化选项
`format`函数还支持各种格式化选项,可以控制插入的值如何显示,以下是一些常用的选项:
### 2.1. 宽度和精度
可以使用`width`和`precision`选项来指定字符串的宽度和精度。
x = 1234567890 print("{:10d}".format(x)) # 宽度为10,左对齐 print("{:10.2f}".format(x)) # 宽度为10,精度为2,左对齐
1234567890 # 宽度为10,左对齐 1.23e+09 # 宽度为10,精度为2,左对齐
### 2.2. 对齐和填充
可以使用`align`和`fill`选项来指定对齐方式和填充字符。
x = 1234567890 print("{:^10d}".format(x)) # 右对齐,用符号填充左边 print("{:010d}".format(x)) # 右对齐,用0填充左边
1234567890 # 右对齐,用符号填充左边 00000001234567890 # 右对齐,用0填充左边
### 2.3. 替换符和格式化字符串的顺序
可以使用替换符(substitution)来指定要格式化的字段名称。
data = {"name": "Alice", "age": 25} print("My name is {} and I am {} years old".format(data["name"], data["age"])) # 使用字典的键作为字段名称
My name is Alice and I am 25 years old # 使用字典的键作为字段名称
还可以使用格式化字符串的顺序来指定要格式化的字段的顺序。
print("{}, {} years old".format("Alice", 25)) # 使用逗号分隔符来指定字段的顺序