我创建了一个Python应用程序,用于从控制台添加Student和Student ID。它工作正常,但输出类似于“ John01”,其中“ John”是学生姓名,“ 01”是学生ID。我正在尝试获得“ John 01”之类的结果。
这是保存文件的功能:
def save_file(student, student_id):
file = open("output.txt", "a")
file.write(student + student_id + "\n")
file.close()
我是Python的新手,不确定如何在函数之间添加空格。
这是我完整的代码:
students = []
def add_student(name, student_id):
student = {"name": name, "student_id": student_id}
students.append(student)
def save_file(student, student_id):
file = open("output.txt", "a")
file.write(student + student_id + "\n")
file.close()
def user_input():
student_name = input("Enter student name: ")
student_id = input("Enter student id: ")
add_student(student_name, student_id)
save_file(student_name, student_id)
add_more()
def add_more():
add_request = input("Do you want to add more student information? (Y/N): ").lower().strip()
if add_request[0] == "y":
return user_input()
else:
print("Student added successfully")
user_input()
除了空间问题外,代码工作正常。这是控制台输出:
Enter student name: John
Enter student id: 01
Do you want to add more student information? (Y/N): y
Enter student name: Jane
Enter student id: 02
Do you want to add more student information? (Y/N): n
Student added successfully
答案 0 :(得分:1)
使用格式功能代替+
file.write("{} {}\n".format(student, student_id))