I have written the code with the idea of leaving some options open regarding formatting:
def init_formatters(n_cols, key_col_len, val_col_len):
line_format = "{:<P}|".replace("P", str(key_col_len)) + (n_cols-1) * "{:>P}|".replace("P", str(val_col_len))
divisor_format = "{:-<P}|".replace("P", str(key_col_len)) + (n_cols-1) * "{:-<P}|".replace("P", str(val_col_len))
return line_format, divisor_format
def format_lines(lines, key_col_len = 10, val_col_len=5):
initialized = False
for line in lines:
tokens = re.split("\s+", line)
if not initialized:
line_format, divisor_format = init_formatters(len(tokens), key_col_len, val_col_len)
print(line_format.format(*tokens))
if not initialized:
initialized = True
print(divisor_format.format(*(len(tokens)*["-"])))
print(divisor_format.format(*(len(tokens)*["-"])))
format_lines
can be called passing the lines you want to format: you can choose a different width for the key column vs the data columns:
l = ["* A05 A12 A15 A19 A23 A24 A25 A26",
"B023 1 0 -1 -- 1 2 3 1",
"B221 1 1 0 -1 -- 1 1 1",
"B260 0 1 1 -1 -1 0 3 2",
"B231 0 0 1 1 -- 6 3 2",
"B456 1 1 -1 1 -1 1 2 4"]
format_lines(l, 5, 4) # this will format the table as desired