Home > Net >  basic formatting a strings in python
basic formatting a strings in python

Time:05-02

Any idea why the count1 variable doesn't format to align to the right?

count1 = 5
games = 7

print(format("correct guesses: %s" %(count1), '>5s'))
print(format("this is how many games played: %s" %(games), '>5s'))

output should be so both numbers align together on the right side so something like this:

correct guesses:                   5
this is how many games played:     7

CodePudding user response:

You need to apply formatting to the string as if there were 2 columns of data:

count1 = 5
games = 7

print("correct guesses:".ljust(30), format("%s" % count1, '>5s'))
print("this is how many games played:".ljust(30), format("%s" % games, '>5s'))

Or using f-strings:

print(f"{'correct guesses:':<30} {count1:>5}")
print(f"{'this is how many games played:':<30} {games:>5}")

Output:

correct guesses:                   5
this is how many games played:     7

CodePudding user response:

Thank you I got it to work with the following:

count1 = 5
games = 7

print(("correct guesses: "), format("%g" %count1, '>19s'))
print(("This is how many games played: "), format("%g" %games, '>5s'))
output was:
correct guesses:                    5
This is how many games played:      7

19 was used to ensure the two lined up due to the extra characters in the string.

  • Related