打印表格的 Pythonic 方式
我正在使用这个简单的函数:
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
并且我假设昵称不超过 15 个字符。
我想保持每个“列”对齐,是否有一些语法糖允许我做同样的事情,但保持昵称列左对齐而不是右对齐,而不破坏右侧的列?
等效的、丑陋的代码是:
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
感谢大家,这是最终版本:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要左对齐而不是右对齐,请使用
%-15s
而不是%15s
。To left-align instead of right-align, use
%-15s
instead of%15s
.稍微偏离主题,但您可以使用
枚举
:Slightly off topic, but you can avoid performing explicit addition on
tot
usingenumerate
:或者,如果您使用 python 2.6,您可以使用 format 方法字符串:
这定义了一个值字典,并将它们用于显示:
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:
看到
p
似乎是一个字典,怎么样:Seeing that
p
seems to be a dict, how about: