0

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
Libra
  • 2,544
  • 1
  • 8
  • 24
  • 2
    Shows us your code, show us your actual output, show us your desired output. Don't make us guess. Your title doesn't really describe your problem. – Tim Roberts Apr 27 '21 at 21:50
  • Are you talking about the *code*, or the *output*? What "lines" that you "just added" are you talking about, and how are you expecting anyone else to have any idea about them? What "responses" are you talking about, and why would they have letters in them? – Karl Knechtel Apr 27 '21 at 21:50
  • 2
    Does https://stackoverflow.com/questions/8450472/how-to-print-a-string-at-a-fixed-width help? – Karl Knechtel Apr 27 '21 at 22:02
  • If I understand correctly, I think all you need to do is add field widths, e.g. `{hair.capitalize():12}`, or whatever you want the column width to be. – Fred Larson Apr 27 '21 at 22:05
  • on page https://pyformat.info/ you can see how to format text – furas Apr 27 '21 at 23:33

1 Answers1

2

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.

Red
  • 26,798
  • 7
  • 36
  • 58