Owen Jakopo
Owen Jakopo

Reputation: 1

How do I space pad my console output in Python?

How do I put spaces between two lines I just added in python, to make it so that the second columns align, regardless of how many letters are in the responses?

Code:

print(f'{email_address}')
print(f'{phone_number}')
print()
print(f'Hair: {hair.capitalize()} Eye color: {eye_color.capitalize()}') 
print(f'Month: {month.capitalize()} Training: {training.capitalize()}')
print('--------------------------------------------------')

I want the hair and the eye_color to be in the same line, the month and the training part to be in the same line as well. I also want them to align regardless of the number of words the user type in. I hope I make sense

This is how I want the last two lines to look like:

Hair: Black     Eye color: Brown
Month: April    Training: Yes

Upvotes: 0

Views: 1310

Answers (1)

Red
Red

Reputation: 27577

You can use the str.ljust() method:

hair = 'Black'
eye_color = 'Brown'
month = 'April'
training = 'Yes'

print(f'Hair: {hair.capitalize()}'.ljust(15), f'Eye color: {eye_color.capitalize()}') 
print(f'Month: {month.capitalize()}'.ljust(15),  f'Training: {training.capitalize()}')

Output:

Hair: Black     Eye color: Brown
Month: April    Training: Yes

Where the 15 in the brackets tells python to make the string at least 15 characters long, adding white-spaces to the end of the string if the string is shorter than 15 characters until is it 15 characters.

If the string was over or equal to 15 characters long to begin with, then the string will remain unchanged.

Upvotes: 2

Related Questions