Trying to format a string into columns with python
Frage
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?
Lösung
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
ofpango.Layout
.Use two labels next to each other and use the method
set_alignment
of the classpango.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.
Andere Tipps
Is something like this acceptable?
>>> names = ["Firstname Lastname", "First Last", "Name Name"]
>>> scores = [49900, 93000, 6400]
>>> for i,v in enumerate(zip(names, scores)):
... name, score = v[0], v[1]
... print "% *d. % -*s %d" % (3, i, 30, name, score)
...
0. Firstname Lastname 49900
1. First Last 93000
2. Name Name 6400
Here the "name" field is padded with spaces to a max width of 30 characters.
Edit: I now see that the width of the font is also a problem. I did not realize that at first from your question. I'll leave this up in case future Googlers end up here for a different reason.