0

I'm a student who is recently been studying the basics of Python. So I faced this problem while doing one of my projects. If someone could explain a solution that is not too complex for my stage I would be grateful.

students = ['Sam', 'Ben', 'John', 'Michael']
marks = [27, 68, 34, 21]
print('Student Name - Mark')
for n in range(0, len(marks)):
    print(students[n], marks[n])

gives the result

Student Name - Mark
Sam 27
Ben 68
John 34
Michael 21

To make it look nicer, I need to take this second list of members which are the marks in a straight vertical line. the expected result is:

Student Name - Mark
Sam            27
Ben            68
John           34
Michael        21

P.S. I was unable to find an answer through google.

  • 1
    Some great answers here: [Create nice column output in python](https://stackoverflow.com/questions/9989334/create-nice-column-output-in-python) – JNevill Oct 20 '22 at 17:54

1 Answers1

0

You can f-string to specify fixed length.

students = ['Sam', 'Ben', 'John', 'Michael']
marks = [27, 68, 34, 21]

print('Student Name - Mark')
for student, mark in zip(students, marks):
    print(f"{student:14} {mark}")

Output:

Student Name - Mark
Sam            27
Ben            68
John           34
Michael        21

Also note the use of zip; for ... in range(len(...)) is usually thought to be un-pythonic.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • I actually didn't know about zip or the f string. I used the last row print(f"{student:{max(len(x) for x in students)}} {mark}") so I don't need guess how long it need to be when it comes to long values. Thanks in advance. – Sachith Jayalath Oct 20 '22 at 19:10
  • @SachithJayalath Yes, that's a better approach, to avoid hard-coded values. – j1-lee Oct 20 '22 at 19:11