输入班级里五个学生的姓名,年龄,班级,成绩(保留两位有效小数),并用三种不同格式化的方法打印出。
时间: 2024-10-23 16:21:24 浏览: 43
当然可以。假设我们有学生数据存储在一个列表中,每个元素包含姓名、年龄、班级和成绩,以下是三种不同的格式化方法来打印:
1. **基本格式打印**:
```python
students = [
{"name": "张三", "age": 18, "class": "一班", "score": 90.50},
{"name": "李四", "age": 17, "class": "二班", "score": 88.85},
{"name": "王五", "age": 16, "class": "三班", "score": 92.20},
{"name": "赵六", "age": 18, "class": "四班", "score": 91.77},
{"name": "刘七", "age": 17, "class": "五班", "score": 89.45}
]
for student in students:
print(f"姓名:{student['name']}, 年龄:{student['age']}, 班级:{student['class']}, 成绩:{student['score']:.2f}")
```
2. **使用字符串格式化(Python f-string)**:
```python
for student in students:
name, age, class_name, score = student.values()
print(f"姓名:{name}, 年龄:{age}, 班级:{class_name}, 成绩:{score:.2f}")
```
3. **使用内置`str.format()`方法**:
```python
for student in students:
formatted_str = "姓名:{},年龄:{},班级:{},成绩:{:.2f}".format(student["name"], student["age"], student["class"], student["score"])
print(formatted_str)
```
阅读全文