How do I align text output in Python?

str.format already has the possibility to specify alignment. You can do that using {0:>5}; this would align parameter 0 to the right for 5 characters. We can then dynamically build a format string using the maximum number of digits necessary to display all numbers equally:

>>> lower = [70, 79, 88, 97, 106, 115]
>>> upper = [78, 87, 96, 105, 114, 123]
>>> num = [5, 3, 4, 2, 6, 4]
>>> digits = len(str(max(lower + upper)))
>>> digits
3
>>> f="{0:>%d}-{1:>%d}: {2}" % (digits, digits)
>>> f
'{0:>3}-{1:>3}: {2}'
>>> for i in range(len(num)):
        print(f.format(lower[i], upper[i], '*' * num[i]))

 70- 78: *****
 79- 87: ***
 88- 96: ****
 97-105: **
106-114: ******
115-123: ****

Actually, you could even use a single format string here with nested fields:

>>> for i in range(len(num)):
        print('{0:>{numLength}}-{1:>{numLength}}: {2}'.format(lower[i], upper[i], '*' * num[i], numLength=digits))

Leave a Comment