Format output string, right alignment
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
00:54 Accepted answer (Score 300)
01:22 Answer 2 (Score 74)
02:05 Answer 3 (Score 66)
02:18 Answer 4 (Score 65)
03:35 Thank you
--
Full question
https://stackoverflow.com/questions/8234...
Accepted answer links:
[str.format]: https://docs.python.org/3/library/string...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #alignment #stringformatting
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping
--
Chapters
00:00 Question
00:54 Accepted answer (Score 300)
01:22 Answer 2 (Score 74)
02:05 Answer 3 (Score 66)
02:18 Answer 4 (Score 65)
03:35 Thank you
--
Full question
https://stackoverflow.com/questions/8234...
Accepted answer links:
[str.format]: https://docs.python.org/3/library/string...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #alignment #stringformatting
#avk47
ACCEPTED ANSWER
Score 328
Try this approach using the newer str.format syntax:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):
line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
ANSWER 2
Score 81
You can align it like that:
print('{:>8} {:>8} {:>8}'.format(*words))
where > means "align to right" and 8 is the width for specific value.
And here is a proof:
>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
print('{:>8} {:>8} {:>8}'.format(*line))
1 128 1298039
123388 0 2
Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).
ANSWER 3
Score 69
It can be achieved by using rjust:
line_new = word[0].rjust(10) + word[1].rjust(10) + word[2].rjust(10)
ANSWER 4
Score 40
I really enjoy a new literal string interpolation in Python 3.6+:
line_new = f'{word[0]:>12} {word[1]:>12} {word[2]:>12}'
Reference: PEP 498 -- Literal String Interpolation