LoginSignup
1
0

More than 3 years have passed since last update.

Pythonで表の文字列長を揃えて表示(CLI)

Last updated at Posted at 2019-07-04

自分用にメモ。

Python 2.7用

表(2次元のリスト)のデータをPythonで整形する

マルチバイト文字は考慮しないで、lenとmaxを使って各列の最大長を取得して揃える

print_table.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
table = [
  ["column1", "column2", "column3"],
  ["abc", "defghijklm", "nopqrstuvwxyz"],
  ["abcdefghi","jklmn", "opqrstuvwxyz"],
]

align_table = [
  ("column1", "r"),
  ("column2", "l"),
  ("column3", "r"),
]

"""
  文字列長が合わないときは空白で埋める
"""
def adjust_length(input_str, adj_length, align='r'):
    return '{:{}{}s}'.format(input_str, {'r': '>', 'l': '<'}[align], adj_length)

max_length = [ max([ len(y) for y in x ]) for x in zip(*table) ]

print("\n".join([
  " ".join([
    adjust_length(x,mlen,align) 
    for x,mlen,align in zip(row,max_length,zip(*align_table)[1])
  ])
  for row in table
]))

実行結果

$ python print_table.py
  column1 column2          column3
      abc defghijklm nopqrstuvwxyz
abcdefghi jklmn       opqrstuvwxyz
$
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0