Make Your Data Shine: Perfecting String Padding and Alignment in Python

Present tabular data elegantly with minimal effort — no external libraries required!

Max N
2 min readApr 5, 2024

Tabular representations pervade daily life, whether organizing financial reports, arranging scientific measurements, or crafting visually appealing terminal outputs. To make your own table look professional, precise string alignment plays a critical role.

Fortunately, vanilla Python comes equipped with robust string formatting mechanisms, enabling easy left-, center-, and right-alignment alongside convenient padding adjustments. Follow along as we demystify these handy utilities together.

Left Align

To create neatly aligned columns with consistent widths, try the rjust method paired with str.format. Start by setting an arbitrary fill character, then specify the desired column width and format specification:

fill_character = "-"
column_width = 10
data = ["Apples", "Pears", "Peaches"]
table = "{:-<{width}}".format("Item", width=column_width)
for value in data:
padded_value = "{}{:<{width}}".format(fill_character, value, width=column_width - len(value))
table += "\n{}".format(padded_value)
print(table)
# Item--------
# Apples
# Pears
# Peaches

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.