align_columns - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: align_columns (/thread-21838.html) |
align_columns - Skaperen - Oct-17-2019 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)) |