Reputation: 39606
I'm using this simple function:
def print_players(players):
tot = 1
for p in players:
print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick'])
tot += 1
and I'm supposing nicks are no longer than 15 characters.
I'd like to keep each "column" aligned, is there a some syntactic sugar allowing me to do the same but keeping the nicknames column left-aligned instead of right-aligned, without breaking column on the right?
The equivalent, uglier, code would be:
def print_players(players):
tot = 1
for p in players:
print '%2d: %s \t (%d|%d) \t was: %s' % (tot, p['nick']+' '*(15-len(p['nick'])), p['x'], p['y'], p['oldnick'])
tot += 1
Thanks to all, here is the final version:
def print_players(players):
for tot, p in enumerate(players, start=1):
print '%2d:'%tot, '%(nick)-12s (%(x)d|%(y)d) \t was %(oldnick)s'%p
Upvotes: 1
Views: 396
Reputation: 6241
Seeing that p
seems to be a dict, how about:
print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p
Upvotes: 2
Reputation: 61609
Slightly off topic, but you can avoid performing explicit addition on tot
using enumerate
:
for tot, p in enumerate(players, start=1):
print '...'
Upvotes: 4
Reputation: 43870
Or if your using python 2.6 you can use the format method of the string:
This defines a dictionary of values, and uses them for dipslay:
>>> values = {'total':93, 'name':'john', 'x':33, 'y':993, 'oldname':'rodger'}
>>> '{total:2}: {name:15} \t ({x}|{y}\t was: {oldname}'.format(**values)
'93: john \t (33|993\t was: rodger'
Upvotes: 3
Reputation: 69480
To left-align instead of right-align, use %-15s
instead of %15s
.
Upvotes: 4