Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating white space in Python so text look aligned

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading