简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM