编写一个python程序,要求输入班级里五个学生的姓名,年龄,班级,成绩(保留两位有效小数),并用三种不同格式化的方法打印出。
时间: 2024-10-21 07:18:09 浏览: 28
编写一个Python程序来满足这个需求,首先我们需要创建一个字典列表来存储每个学生的信息,然后我们可以使用`str.format()`、f-string以及`'{:.2f}'.format()`来分别展示数据。以下是三种不同格式化的示例:
```python
# 学生信息字典列表
students = [
{"name": "张三", "age": 18, "class": "一班", "score": 90.56},
{"name": "李四", "age": 17, "class": "二班", "score": 88.75},
{"name": "王五", "age": 19, "class": "三班", "score": 95.43},
{"name": "赵六", "age": 16, "class": "四班", "score": 82.11},
{"name": "刘七", "age": 18, "class": "五班", "score": 91.00}
]
# 使用str.format()
for student in students:
print("名字: {}, 年龄: {}, 班级: {}, 成绩: {:.2f}".format(student["name"], student["age"], student["class"], student["score"]))
# 使用f-string
for student in students:
print(f"名字: {student['name']}, 年龄: {student['age']}, 班级: {student['class']}, 成绩: {student['score']: .2f}")
# 使用'{:.2f}'.format()
formatted_scores = [f"{s['score']: .2f}" for s in students]
for i, (student, score) in enumerate(zip(students, formatted_scores)):
print(f"第{i+1}名:名字: {student['name']}, 年龄: {student['age']}, 班级: {student['class']}, 成绩: {score}")
```
阅读全文