How do you print the ascii table in python?

This program prints ASCII table in Python programming language using while loop and built-in function chr[].

Function chr[] returns a Unicode string of one character.

Python Source Code: ASCII Table


digit = 0

while digit None:

        min_len = len[min[[v for v in table.values[]], key=lambda q: len[q]]]
        max_len = len[max[[v for v in table.values[]], key=lambda q: len[q]]]

        if min_len < max_len:
            stderr.write["Table is out of shape, please make sure all columns have the same length."]
            stderr.flush[]
            return

        additional_spacing = 1

        heading_separator = '| '
        horizontal_split = '| '

        rc_separator = ''
        key_list = list[table.keys[]]
        rc_len_values = []
        for key in key_list:
            rc_len = len[max[[v for v in table[key]], key=lambda q: len[str[q]]]]
            rc_len_values += [[rc_len, [key]] for n in range[len[table[key]]]]

            heading_line = [key + [" " * [rc_len + [additional_spacing + 1]]]] + heading_separator
            stdout.write[heading_line]

            rc_separator += ["-" * [len[key] + [rc_len + [additional_spacing + 1]]]] + '+-'

            if key is key_list[-1]:
                stdout.flush[]
                stdout.write['\n' + rc_separator + '\n']

        value_list = [v for vl in table.values[] for v in vl]

        aligned_data_offset = max_len

        row_count = len[key_list]

        next_idx = 0
        newline_indicator = 0
        iterations = 0

        for n in range[len[value_list]]:
            key = rc_len_values[next_idx][1][0]
            rc_len = rc_len_values[next_idx][0]

            line = ['{:{}} ' + " " * len[key]].format[value_list[next_idx], str[rc_len + additional_spacing]] + horizontal_split

            if next_idx >= [len[value_list] - aligned_data_offset]:
                next_idx = iterations + 1
                iterations += 1
            else:
                next_idx += aligned_data_offset

            if newline_indicator >= row_count:
                if full_row:
                    stdout.flush[]
                    stdout.write['\n' + rc_separator + '\n']
                else:
                    stdout.flush[]
                    stdout.write['\n']

                newline_indicator = 0

            stdout.write[line]
            newline_indicator += 1

        stdout.write['\n' + rc_separator + '\n']
        stdout.flush[]

Example:

table = {
        "uid": ["0", "1", "2", "3"],
        "name": ["Jon", "Doe", "Lemma", "Hemma"]
    }

create_table[table]

Output:

uid   | name       | 
------+------------+-
0     | Jon        | 
1     | Doe        | 
2     | Lemma      | 
3     | Hemma      | 
------+------------+-

answered Sep 1, 2017 at 19:20

1

Here's my solution:

def make_table[columns, data]:
    """Create an ASCII table and return it as a string.

    Pass a list of strings to use as columns in the table and a list of
    dicts. The strings in 'columns' will be used as the keys to the dicts in
    'data.'

    Not all column values have to be present in each data dict.

    >>> print[make_table[["a", "b"], [{"a": "1", "b": "test"}]]]
    | a | b    |
    |----------|
    | 1 | test |
    """
    # Calculate how wide each cell needs to be
    cell_widths = {}
    for c in columns:
        values = [str[d.get[c, ""]] for d in data]
        cell_widths[c] = len[max[values + [c]]]

    # Used for formatting rows of data
    row_template = "|" + " {} |" * len[columns]

    # CONSTRUCT THE TABLE

    # The top row with the column titles
    justified_column_heads = [c.ljust[cell_widths[c]] for c in columns]
    header = row_template.format[*justified_column_heads]
    # The second row contains separators
    sep = "|" + "-" * [len[header] - 2] + "|"
    # Rows of data
    rows = []
    for d in data:
        fields = [str[d.get[c, ""]].ljust[cell_widths[c]] for c in columns]
        row = row_template.format[*fields]
        rows.append[row]

    return "\n".join[[header, sep] + rows]

answered Jul 16, 2016 at 15:35

Luke TaylorLuke Taylor

7,6778 gold badges52 silver badges87 bronze badges

This can be done with only builtin modules fairly compactly using list and string comprehensions. Accepts a list of dictionaries all of the same format...

def tableit[dictlist]:
    lengths = [ max[map[lambda x:len[x.get[k]], dictlist] + [len[k]]] for k in dictlist[0].keys[] ]
    lenstr = " | ".join["{:

Chủ Đề