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

Strings not being centered when printing

I am making something for my girlfriend, but there’s a problem: the text is not being centered!

main.py:

from zari import Zari

attributes = [a for a in vars(Zari) if not a.startswith('__')]
for attribute in attributes:
  print(attribute, "=".center(5), getattr(Zari, attribute))

prints

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

love   =   999999999999999999999999999999999999999999999999999999
smarts   =   9 <-- the issue is on this line 
looks   =   99999999999999999999999999
humor   =   99999999999

The equals sign isn’t aligned with the others…

How do I do this?

>Solution :

I’m not sure what you were expecting by centering just the equals sign, but assuming you want to align the equals sign vertically you can do as follows.

Given

arr = [('love', 999999999999999999999999999999999999999999999999999999),
       ('smarts', 9),
       ('looks', 99999999999999999999999999),
       ('humor', 99999999999)]

You could left justify the first column with

for x, y in arr:
    print(f'{x:<6} = {y}')

giving

love   = 999999999999999999999999999999999999999999999999999999
smarts = 9
looks  = 99999999999999999999999999
humor  = 99999999999

or right justify with

for x, y in arr:
    print(f'{x:>6} = {y}')

giving

  love = 999999999999999999999999999999999999999999999999999999
smarts = 9
 looks = 99999999999999999999999999
 humor = 99999999999
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