How to Align Text in Two Columns with ljust in Python
Format pairs of strings into two aligned columns using ljust padding.
Python code
11 linesitems = [
("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
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
- Use f-string formatting like f"{name:<{col1_width}}{color}"
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.