ASCII Table Alignment Function

  • Share this:

Code introduction


This function takes two lists as input. The first list contains the strings to be printed, and the second list contains the widths of each string. The function aligns the strings to the specified width and prints them as a table.


Technology Stack : list, string, integer, generator expression

Code Type : Text processing

Code Difficulty : Intermediate


                
                    
def ascii_table(arg1, arg2):
    if not isinstance(arg1, list) or not all(isinstance(i, str) for i in arg1):
        raise ValueError("arg1 must be a list of strings")
    if not isinstance(arg2, list) or not all(isinstance(i, int) for i in arg2):
        raise ValueError("arg2 must be a list of integers")
    if len(arg1) != len(arg2):
        raise ValueError("The length of arg1 and arg2 must be the same")

    table = ""
    for i in range(max(arg2)):
        for j, (text, width) in enumerate(zip(arg1, arg2)):
            table += text.rjust(width)
        table += "\n"
    return table