生成单独的代码片段并将它们合并:
print ' '.join(['%-2s' % (i,) for i in l])
或者您可以使用字符串乘法:
print ('%-2s ' * len(l))[:-1] % tuple(l)
[:-1]
移除末尾的额外空格;你也可以使用
.rstrip()
。
演示:
>>> print ' '.join(['%-2s' % (i,) for i in l])
AA BB CC DD
>>> print ' '.join(['%-2s' % (i,) for i in (l + l)])
AA BB CC DD AA BB CC DD
>>> print ('%-2s ' * len(l))[:-1] % tuple(l)
AA BB CC DD
>>> print ('%-2s ' * len(l))[:-1] % tuple(l + l)
AA BB CC DD AA BB CC DD
时间统计:
>>> def joined_snippets(l):
... ' '.join(['%-2s' % (i,) for i in l])
...
>>> def joined_template(l):
... ' '.join(['%-2s' for i in l])%tuple(l)
...
>>> def multiplied_template(l):
... ('%-2s ' * len(l))[:-1] % tuple(l)
...
>>> from timeit import timeit
>>> l = ["AA","BB","CC","DD"]
>>> timeit('f(l)', 'from __main__ import l, joined_snippets as f')
1.3180170059204102
>>> timeit('f(l)', 'from __main__ import l, joined_template as f')
1.080280065536499
>>> timeit('f(l)', 'from __main__ import l, multiplied_template as f')
0.7333378791809082
>>> l *= 10
>>> timeit('f(l)', 'from __main__ import l, joined_snippets as f')
10.041708946228027
>>> timeit('f(l)', 'from __main__ import l, joined_template as f')
5.52706503868103
>>> timeit('f(l)', 'from __main__ import l, multiplied_template as f')
2.8013129234313965
乘法模板选项使其他选项相形见绌。
print "%-2s ... %-2s" % tuple(l)
。我之前用join做过,但我想知道是否有一些内置的支持。再次感谢。 - user1692261'%-2s '*len(l)%tuple(l)
,但是这会在末尾留下一个额外的空格。不过这对你可能没有影响。 - John La Rooy