How to Align Text in Two Columns with ljust in Python

Format pairs of strings into two aligned columns using ljust padding.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

11 lines
Python 3.9+
items = [
    ("apple", "red"),
    ("banana", "yellow"),
    ("cherry", "dark red"),
    ("date", "brown")
]

col1_width = max(len(name) for name, _ in items) + 2

for name, color in items:
    print(name.ljust(col1_width) + color)

Output

stdout
apple     red
banana    yellow
cherry    dark red
date      brown

How it works

The ljust method pads the string on the right with spaces to a specified width, ensuring uniform column alignment. By computing the maximum length of the first column's entries and adding padding, we create a fixed width that works for all rows. Concatenating the padded first column with the second column yields a clean two-column layout. This approach is purely stdlib and works with any iterable of pairs.

Common mistakes

  • Forgetting to add extra padding after max length, causing columns to touch
  • Using a fixed width that's too small for longer items
  • Not converting non-string values to strings before using ljust

Variations

  1. Use f-string formatting like f"{name:<{col1_width}}{color}"
  2. Use the `format` method with alignment specifiers

Real-world use cases

  • Printing tabular data from database queries in command-line tools.
  • Generating aligned reports or logs for system monitoring scripts.
  • Formatting API response fields into readable text for debugging output.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.