Building a Robust Markdown Table Formatter in Python
When generating markdown documentation programmatically, formatting clean tables with consistent alignment (left, right, center) is often a repetitive and error-prone task.
In this article, we explore a lightweight, zero-dependency Python SDK designed to format tables cleanly and reliably.
The Formatter Implementation
Here is how the core formatter is built:
class MarkdownTableFormatter:
def __init__(self, alignment: str = "left"):
self.alignment = alignment
def format_row(self, cells: list) -> str:
return "| " + " | ".join(str(c) for c in cells) + " |"
def format_table(self, headers: list, rows: list) -> str:
if not headers and not rows:
return ""
if not headers:
headers = ["" for _ in range(len(rows[0]))] if rows else []
lines = [self.format_row(headers)]
sep = []
for h in headers:
if self.alignment == "right":
sep.append("---:")
elif self.alignment == "center":
sep.append(":---:")
else:
sep.append(":---")
if headers:
lines.append("| " + " | ".join(sep) + " |")
for r in rows:
lines.append(self.format_row(r))
return "\n".join(lines)
Features & Testing
- Fully tested with Unit Tests covering empty states, alignments, and custom columns.
- Zero external dependencies.
- Perfect for CLI tools, static site generators, and automated reporting.
Support my open-source work via crypto (Base): 0x551a468628F6F35546E11dAcDa3d99EE75E61A8D or PayPal: buidangvinhquang@gmail.com.
Top comments (0)