.format()拼合
时间: 2024-03-19 21:38:47 浏览: 10
`.format()`是Python中用于字符串格式化的方法。它可以将变量的值插入到字符串中的占位符位置。面是`.format()`拼合的一些基本用法:
1. 位置参数:可以通过位置来指定要插入的变量值。例如:
```
name = "Alice"
age = 25
message = "My name is {}, and I am {} years old.".format(name, age)
print(message)
```
输出:`My name is Alice, and I am 25 years old.`
2. 关键字参数:可以通过关键字来指定要插入的变量值。例如:
```
name = "Bob"
age = 30
message = "My name is {name}, and I am {age} years old.".format(name=name, age=age)
print(message)
```
输出:`My name is Bob, and I am 30 years old.`
3. 格式化限定符:可以在占位符中使用格式化限定符来控制变量值的显示格式。例如:
```
pi = 3.1415926
message = "The value of pi is {:.2f}".format(pi)
print(message)
```
输出:`The value of pi is 3.14`
4. 索引和属性访问:可以通过索引或属性访问来获取变量值。例如:
```
person = ("Alice", 25)
message = "My name is {0[0]}, and I am {0[1]} years old.".format(person)
print(message)
```
输出:`My name is Alice, and I am 25 years old.`