使用Python的format函数写三句话
时间: 2024-09-26 14:12:14 浏览: 43
`format()` 函数是 Python 中一种强大的字符串格式化工具,它允许你在运行时动态插入变量到字符串中。以下是三个例子:
1. **基本格式化**:
```python
name = "Alice"
age = 25
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence) # 输出: My name is Alice and I am 25 years old.
```
2. **字段命名**:
```python
score = 90
percentage = score / 100 * 100
sentence = "{name}'s score is {score} which is {percentage:.2f}%".format(name="John", score=score, percentage=percentage)
print(sentence) # 输出: John's score is 90 which is 90.00%
```
3. **关键字参数**:
```python
name = "Bob"
hobbies = ["reading", "gaming"]
sentence = "I like to {hobbies[0]} in my free time. Also, I enjoy {hobbies[1]}."
print(sentence.format(hobbies=hobbies)) # 输出: I like to reading in my free time. Also, I enjoy gaming.
```
阅读全文