So I've got a function which creates a little star table based on some data collected elsewhere in the program. While the table produces the correct output, since the number of characters in each number changes, it un-aligns the table. For example,
70-78: *****
79-87: ***
88-96: ****
97-105: **
106-114: ******
115-123: ****
Is there any way to make the stars align (hehe) so that the output is something like this:
70-78: *****
79-87: ***
88-96: ****
97-105: **
106-114: ******
115-123: ****
Here's how I currently print the table.
for x in range(numClasses):
print('{0}-{1}: {2}'.format(lower[x],upper[x],"*"*num[x]))
To set the alignment, use the character < for left-align, ^ for center, > for right.
Python String center() Method The center() method will center align the string, using a specified character (space is default) as the fill character.
Alignment of Strings Using the format() Method in Python To left-align a string, we use the “:<n” symbol inside the placeholder. Here n is the total length of the required output string. Left Aligned String with length 10 is: Scaler . To right align a string, we use the “:>n” symbol inside the placeholder.
You can align values within a specified length of text by using the < , > , or ^ symbols to specify left align, right align, or centering, respectively. Then you follow the those symbols with a character width you desire.
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))
This should do the trick. I assume there are clever ways.
print '70-78:'.ljust(10) + '*****'
You could also use expandtabs()
print ('70-78'+'\t'+ '*****').expandtabs(10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With