How to indent words with the '%s' format specifier?

Viewed 26

The title. I am trying to indent some words so the colons are aligned, but the '%s' format specifier isn't working for some reason. I've tried changing the number value, adding decimal points, and changing s to d or f but nothing's working. Any help would be appreciated.

Assignment1 = float(input('Enter score of first assignment (0-4.0):'))  
Assignment2 = float(input('Enter score of second assignment (0-4.0):'))
Assignment3 = float(input('Enter score of third assignment (0-4.0):'))
Midterm = float(input('Enter Midterm score (0-4.3):'))
Final = float(input('Enter Final Exam score (0-4.3):'))
WeightedExam = ((Midterm*0.20)+(Final*0.30))
WeightedAssignment = ((Assignment3*0.20)+(Assignment1*0.15)+(Assignment2*0.15))

print("%8s %0.1f \t %0.1f \t %0.1f" %("Assignment Scores:", Assignment1, Assignment2, Assignment3))
print("%10s %0.1f \t %0.1f" %("Exam Scores:", Midterm, Final))
print("%0s %0.1f \t %0.1f" %("Weighted Exams/Assignments:", WeightedExam, WeightedAssignment))
2 Answers

You are using a field width that's less that the width of the string you're trying to print. This will have no effect.

Consider:

>>> "%3s" % "foo bar"
'foo bar'

But if we use a field width that's greater than the width of the string:

>>> "%10s" % "foo bar"
'   foo bar'
>>> "%-10s" % "foo bar"
'foo bar   '

Of course, you may want to replace the % of formatting strings with f-strings.

You can use the rjust method

print('Assignment Scores:'.rjust(30,' '), "%0.1f \t %0.1f \t %0.1f" %(Assignment1, Assignment2, Assignment3))
print('Exam Scores:'.rjust(30,' '), "%0.1f \t %0.1f" %(Midterm, Final))
print('Weighted Exams/Assignments:'.rjust(30,' '), "%0.1f \t %0.1f" %(WeightedExam, WeightedAssignment))
Related