CLI table draw in Python
Table of Contents
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:
become
mb_strlen( cellContent )
len(str( cellContent ))
- Column names:
become
$key.str_repeat(" ",$columnWidths[$key] - mb_strlen($key))
key.ljust( maxLenghts[key] )
- Horizontal lines:
become
str_repeat("─",$columnWidths[$key])
"".ljust( maxLenghts[key], "─")
- Data cell:
become
$cell .= str_repeat(" ", $columnWidths[$key] - mb_strlen($cell))
(some cells contain numbers, thats whystr(cell).ljust( maxLenghts[key] )
str(..)
) - Drawing table header:
become
echo "â•â”€".implode("─┬─", $horizontalLines)."─╮\n"; echo "│ ".implode(" │ ", $columnNames )." │\n"; echo "├─".implode("─┼─", $horizontalLines)."─┤\n";
Pho associative key/value arrays are python dictionaries, andprint("â•â”€"+"─┬─".join(horizontalLines.values())+"─╮"); print("│ "+" │ ".join(columnNames.values() )+" │"); print("├─"+"─┼─".join(horizontalLines.values())+"─┤");
join
will concatenate dictionary keys, not values in python. So we need.values()
to turn it into array of values only. - Drawing data row:
bacome
echo "│ ".implode(" │ ", $row)." │\n";
print("│ "+" │ ".join(row.values())+" │")
- Drawing table footer
become
echo "╰─".implode("─┴─", $horizontalLines)."─╯\n";
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 🤑