Search code examples
pythonstring-formattingpretty-print

Python - print table-like data cleanly


I have output that looks like this

AB%CD3_SW3Z_1000 uvsec_czrkup_rmplr SeightRveZargrp def_move 35.8% 28.0% 16.2% 120 0.0010
MN%P03_AT%W00_500 uvsec_czrkup_rmplr SeightRveZargrp def_move 28.8% 24.7% 23.4% 94 0.1000
KE_A03_UVA%Q00_100 uvsec_czrkup_rmplr SeightRveZargrp def_move 27.2% 11.8% 3.5% 398 0.010

What is the cleanest, most elegant way to format it as

AB%CD3_SW3Z_1000   uvsec_czrkup_rmplr SeightRveZargrp def_move 35.8% 28.0% 16.2% 120 0.0010
MN%P03_AT%W00_500  uvsec_czrkup_rmplr SeightRveZargrp def_move 28.8% 24.7% 23.4% 94 0.1000
KE_A03_UVA%Q00_100 uvsec_czrkup_rmplr SeightRveZargrp def_move 27.2% 11.8% 3.5% 398 0.010

Of course, I am asking in general case, assuming each line has the same number of tokens. I want columns to be left-alligned.


Solution

  • I have used PrettyTables for this type of application in the past and this function:

    def format_df(df):    
        table = PrettyTable([''] + list(df.columns))
        for row in df.itertuples():
            table.add_row(row)
        return str(table)
    

    A full example, using your input looks like this:

    import pandas as pd
    from prettytable import PrettyTable
    
    def format_df(df):    
        table = PrettyTable([''] + list(df.columns))
        for row in df.itertuples():
            table.add_row(row)
        return str(table)
    
    df = pd.read_clipboard(header=None)   # No header provided on example input
    print(format_df(df))
    

    This generates the following output. The headers are named poorly because there were not headers provided in your sample data:

    +---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+
    |   |         0          |         1          |        2        |    3     |   4   |   5   |   6   |  7  |   8   |
    +---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+
    | 0 |  AB%CD3_SW3Z_1000  | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 35.8% | 28.0% | 16.2% | 120 | 0.001 |
    | 1 | MN%P03_AT%W00_500  | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 28.8% | 24.7% | 23.4% |  94 |  0.1  |
    | 2 | KE_A03_UVA%Q00_100 | uvsec_czrkup_rmplr | SeightRveZargrp | def_move | 27.2% | 11.8% |  3.5% | 398 |  0.01 |
    +---+--------------------+--------------------+-----------------+----------+-------+-------+-------+-----+-------+