Python

CLI table draw in Python

Well.. I migrated all my current project to python 😅

Recipie is the same: fill all cells with spaces to maximum column length, then concatenate array representing table row using separator. Flavor with special chars like “├”.

Implemetation changed from Php CLI how to draw table , but not really much:

  • Multibyte string length:
    mb_strlen( cellContent )
    
    become
    len(str( cellContent ))
    
  • Column names:
    $key.str_repeat(" ",$columnWidths[$key] - mb_strlen($key))
    
    become
    key.ljust( maxLenghts[key] )
    
  • Horizontal lines:
    str_repeat("─",$columnWidths[$key])
    
    become
    "".ljust( maxLenghts[key], "─")
    
  • Data cell:
    $cell .= str_repeat(" ", $columnWidths[$key] - mb_strlen($cell))
    
    become
    str(cell).ljust( maxLenghts[key] )
    
    (some cells contain numbers, thats why str(..))
  • Drawing table header:
    echo "╭─".implode("─┬─", $horizontalLines)."─╮\n";
    echo "│ ".implode(" │ ", $columnNames    )." │\n";
    echo "├─".implode("─┼─", $horizontalLines)."─┤\n";
    
    become
    print("╭─"+"─┬─".join(horizontalLines.values())+"─╮");
    print("│ "+" │ ".join(columnNames.values()    )+" │");
    print("├─"+"─┼─".join(horizontalLines.values())+"─┤");
    
    Pho associative key/value arrays are python dictionaries, and join will concatenate dictionary keys, not values in python. So we need .values() to turn it into array of values only.
  • Drawing data row:
    echo "│ ".implode(" │ ", $row)." │\n"; 
    
    bacome
    print("│ "+" │ ".join(row.values())+" │")
    
  • Drawing table footer
    echo "╰─".implode("─┴─", $horizontalLines)."─╯\n";
    
    become
    print("╰─"+"─┴─".join(horizontalLines.values())+"─╯")
    

That’s it 😊

Should I make nice function, like in previous post? 🤔 I doubt that it’s really nesessary, but if you want it - drop me a message with “buy me a coffee” widget in bottom-right corner 🤑