Python Forum
writing all new scripts in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing all new scripts in Python
#8
here's one of my simple commands. when you have output from a command that has columns that are not aligned vertically, this script command lines it up by getting the maximum width of each column then justifying each column of each row to that size, padded with spaces, left justified, except for decimal numbers right justified. it also takes data in arguments as a convenience for shell scripts.

http://ipal.net/python/align_columns.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Line up columns of input text."""
from sys import argv,stdin
argv.pop(0)
size = [] # indexed by col number
rows = [] # indexed by row number
for data in argv if argv else stdin:
    # in case an argument has 2 or more lines;
    for line in data.splitlines():
        cols = tuple(line.split())
        rows.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 row in rows:
    new = []
    n = 0
    for col in row:
        if col.isdecimal():
            new.append(col.rjust(size[n]))
        else:
            new.append(col.ljust(size[n]))
        n += 1
    print(' '.join(new).rstrip())
Tradition is peer pressure from dead people

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


Messages In This Thread
writing all new scripts in Python - by Skaperen - Nov-09-2019, 03:46 AM
RE: writing all new scripts in Python - by Larz60+ - Nov-09-2019, 11:16 AM
RE: writing all new scripts in Python - by Skaperen - Nov-10-2019, 01:33 AM
RE: writing all new scripts in Python - by Larz60+ - Nov-10-2019, 02:43 AM
RE: writing all new scripts in Python - by Skaperen - Nov-10-2019, 09:07 PM
RE: writing all new scripts in Python - by Skaperen - Nov-10-2019, 11:24 PM

Forum Jump:

User Panel Messages

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