テーブルを印刷するPythonの方法
-
05-07-2019 - |
質問
この単純な関数を使用しています:
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
解決
p
が辞書のように見えるのを見て、どうですか:
print '%2d' % tot + ': %(nick)-15s \t (%(x)d|%(y)d) \t was: %(oldnick)15s' % p
他のヒント
右揃えではなく左揃えにするには、%15s
ではなく%-15s
を使用します。
トピックから少し外れていますが、 tot に明示的に追加することを避けることができます= "nofollow noreferrer"> 列挙
:
for tot, p in enumerate(players, start=1):
print '...'
またはPython 2.6を使用している場合は、 format 文字列のメソッド:
これは値の辞書を定義し、それらをディップスレイに使用します:
>>> 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'
所属していません StackOverflow