Skip to content

How to Add Padding to Strings in Python

Learn how to use Python's .ljust(), .rjust(), .center(), .zfill(), and f-string formatting ({val:<w}, {val:>w}) to align text, pad numbers with zeros, and create consistent-width outputs for logs, tables, and reports.

Padding is a critical technique for aligning text, formatting logs, and ensuring numbers (like IDs or dates) have a uniform length (e.g., 001, 002). Python provides several elegant ways to add filler characters to the beginning, end, or both sides of a string, ranging from classic string methods to modern, powerful f-strings.

Using String Methods (Quick & Readable)

Python strings include three built-in methods designed for alignment: .ljust(), .rjust(), and .center(). By default, they use a space for padding, but you can specify any custom character.

text = "Level"

print(f"'{text.ljust(10)}'")

print(f"'{text.rjust(10)}'")

print(f"'{text.center(11, '-')}'")

Modern Formatting with F-Strings

Introduced in Python 3.6, f-strings provide a concise syntax for padding directly inside a string literal. This is the preferred method for modern Python development as it is faster and more expressive.

score = 42


print(f"'{score:<8}'")  # Output: '42      '

print(f"'{score:*>8}'") # Output: '******42'

Specific Case: Zero Padding with zfill()

When you need to pad numbers with leading zeros (common in serial numbers or time stamps), the .zfill() method is the most semantic choice.

id_code = "125"

print(id_code.zfill(6)) # Output: '000125'

Summary of Alignment Operators

Purpose Method F-String Syntax
Align Left .ljust(w) {val:<w}
Align Right .rjust(w) {val:>w}
Align Center .center(w) {val:^w}
Leading Zeros .zfill(w) {val:0>w}

By mastering these padding techniques, you can ensure your terminal outputs, logs, and generated reports look professional and remain perfectly aligned regardless of the input data.

Navigation