Skip to content

How to Align Output in Python Printings

Learn how to use Python's string alignment methods (ljust, rjust, center) and f-strings to format CLI tables, reports, and logging for cleaner, more readable output.

Presenting output in a clean, organized manner is essential for CLI tools, reports, and logging. Python provides multiple ways to align text, from basic string methods to powerful formatting expressions. Whether you need to create tabular data or simply center a title, proper alignment improves code readability and user experience.

This guide explores the standard string methods for alignment (ljust, rjust, center) and the modern, more flexible approach using f-string.

Basic String Methods

Python strings have built-in methods specifically for padding and alignment. These are straightforward to use for simple tasks.

  • str.ljust(width, fillchar): Left align.
  • str.rjust(width, fillchar): Right align.
  • str.center(width, fillchar): Center align.

Simple Padding

The width argument determines the total length of the resulting string. If the original string is shorter than the width, padding is added.

text = "Python"

left  = text.ljust(15)
right = text.rjust(15)
mid   = text.center(15)

print(f"|{left}|")
print(f"|{right}|")
print(f"|{mid}|")

Output:

|Python         |
|         Python|
|     Python    |

Custom Fill Characters

You can specify a character other than a space for padding.

text = "Chapter 1"

toc_entry = text.ljust(20, '.')
title     = "Menu".center(20, '=')

print(toc_entry + " Page 5")
print(title)

Output:

Chapter 1........... Page 5
========Menu========

Modern Formatting with f-string

Introduced in Python 3.6, f-string (Formatted String Literals) are the recommended way to format text. They allow you to embed expressions and specify alignment logic concisely inside the curly braces {}.

Syntax: {value:align_char width}

  • <: Left align
  • >: Right align
  • ^: Center align
name = "Alice"
score = 95.5


print(f"|{name:<10}|") 
print(f"|{name:>10}|")
print(f"|{name:^10}|")

print(f"Player: {name:<10} Score: {score:>8.2f}")

Output:

|Alice     |
|     Alice|
|  Alice   |
Player: Alice      Score:    95.50

Building Formatted Tables

To create a clean CLI table, you need to define consistent widths for your columns and apply them to both the header and the data rows.

data = [
    ("Laptop", 1200.50),
    ("Mouse", 25.00),
    ("HDMI Cable", 12.99)
]

w_item = 15
w_price = 10

print(f"{'Item':<{w_item}} {'Price':>{w_price}}")
print("-" * (w_item + w_price + 2))

for item, price in data:
    print(f"{item:<{w_item}} ${price:>{w_price}.2f}")

Output:

Item                 Price
---------------------------
Laptop          $   1200.50
Mouse           $     25.00
HDMI Cable      $     12.99

Dynamic Column Widths

Hardcoding widths (like 15 above) can truncate long data. A robust approach calculates the maximum width required based on the data content.

data = [
    ("Alice Smith", "Engineer", 35),
    ("Bob Jones", "Data Scientist", 42),
    ("Charlie", "Intern", 21)
]

headers = ["Name", "Role", "Age"]

col1_w = max(len(row[0]) for row in data + [headers]) + 2
col2_w = max(len(row[1]) for row in data + [headers]) + 2
col3_w = max(len(str(row[2])) for row in data + [headers]) + 2

print(f"{headers[0]:<{col1_w}}{headers[1]:<{col2_w}}{headers[2]:>{col3_w}}")
print("-" * (col1_w + col2_w + col3_w))

for name, role, age in data:
    print(f"{name:<{col1_w}}{role:<{col2_w}}{age:>{col3_w}}")

Output:

Name         Role              Age
----------------------------------
Alice Smith  Engineer           35
Bob Jones    Data Scientist     42
Charlie      Intern             21

Conclusion

Aligning text in Python transforms raw data into professional, readable output.

  1. Use Basic Methods (ljust, center) for simple string manipulation or custom padding characters.
  2. Use f-string ({val:<10}) for most printing tasks, as they are concise and performant.
  3. Use Dynamic Calculation for tables to ensure columns adapt to your data size without manual tweaking.
Navigation