简体   繁体   中英

Pythonic way to print a table

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

要左对齐而不是右对齐,请使用%-15s而不是%15s

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

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

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'

看到p似乎是一个决定,如何:

print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM