Python Forum

Full Version: align_columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i've needed this command many times and only today decided to finally code it. i'm sure it is not as simple or pythonic as it could be. i made it for a command line environment where i can pipe the (non-aligned columns) output of one command to the input of another. it can also take lines from command line arguments. this is untested in Python2.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sys import argv,stdin

argv.pop(0)
size = []
hold = []
for data in argv if argv else stdin:
    for line in data.splitlines():
        cols = tuple(line.split())
        hold.append(cols)
        x = len(cols)
        y = len(size)
        if y<x:
            size[:] = size+(x-y)*[1]
        for n in range(x):
            size[n] = max(size[n],len(cols[n]))

for cols in hold:
    new = []
    n = 0
    for col in cols:
        if col.isdecimal():
            new.append(col.rjust(size[n]))
        else:
            new.append(col.ljust(size[n]))
        n += 1
    print(' '.join(new))