Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
align_columns
#1
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))
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020