Strings not being centered when printing
Question:
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?
Answers:
I recommend using str.format
as in this thread instead of center
.
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
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 recommend using str.format
as in this thread instead of center
.
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