Creating white space in Python so text look aligned

Question:

I have the following code:

names = ['William T. Riker', 'Jean-Luc Picard', 'Worf', 'Deanna Troi']

function ='The Team'

for name in names:
    print(name,":", function)

This produces the following output:

William T. Riker : The Team
Jean-Luc Picard : The Team
Worf : The Team
Deanna Troi : The Team

The project which I am coding will produce a lot of lines but its a little disorienting when different names will align text differently; As in the example above. How can I make the print statement so that it looks like the example below?

William T. Riker : The Team
Jean-Luc Picard  : The Team
Worf             : The Team
Deanna Troi      : The Team

I already know the maximum length of character in name variable. How can i create white space so the text will always align in a manner as outlined in the example above.

Asked By: Slartibartfast

||

Answers:

Try this small change to find max length first

max_len = max(len(x) for x in names)

for name in names:
    print(name.ljust(max_len),":", function)
Answered By: mad_
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.