views:

130

answers:

4

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
+4  A: 

To left-align instead of right-align, use %-15s instead of %15s.

Paul Stephenson
+2  A: 

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
RichN
+3  A: 

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'
monkut
what does `**values` mean? I saw `**` only in parameters declaration (declaration of a function/method).
Andrea Ambu
@Andrea: it passes the key/value pairs of a dictionary as a series of named arguments to a function. So, if `d = {'a': 1, 'b': 2}`, then `f(**d)` is equivalent to `f(a=1, b=1)`.
Stephan202
I didn't know that, thank you very much!
Andrea Ambu
(should be `f(a=1, b=2)` of course, sorry for the typo.)
Stephan202
And use '{nick:<15}' for left-align. In original context, you want: print '{tot:2}: {nick:<15} \t ({x}|{y}) \t was: {oldnick:15}'.format(tot=tot, **p)
Beni Cherniavsky-Paskin
+3  A: 

Slightly off topic, but you can avoid performing explicit addition on tot using enumerate:

for tot, p in enumerate(players, start=1):
    print '...'
Stephan202