I am trying to format a string to display two columns for a high score table. Python is able to do this well when using print
print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
but when trying to use a formatted string, but becomes more challenging it seems. This is the result I am trying to get:
#for name, score in list: prints the following
1. FirstName LastName 45000
2. First LastName 78000
3. Fst Lst 11123
4. Name Name 40404
5. llll lll 12345
This is all one string that goes into a pygtk label. Currently I have this:
score_string += "%i. %-15.12s\t%15s\n" % (index, name, score)
which yields untrustworthy results. My current test data is displayed as the following:
1. Firstname Lastname 49900
2. First Last 93000
3. Name Name 6400
Because the first name in that list is longer than the rest (in width, not count of characters) the tab forces the score out of position. Is there a way to do this that not only takes the length of the string, but the width of the string into account as well?
You have two options:
Change the font of the PyGTK label to a font that has equal width characters (not unreasonable in a game, it reminds us of the old arcade days). You can do this with set_markup
of pango.Layout
.
Use two labels next to each other and use the method set_alignment
of the class pango.Layout
. The first label aligns the name to the left, the second label contains the score and it aligns to the right. As long as their is enough space the names and scores will align nicely to the left and right respectively.