Python Basics — String Formatting

2 minute read

String Formatting

Python offers multiple ways to format strings. Understanding all of them helps you read existing code, but for new code, f-strings are the recommended approach.

Method 1: % Operator (Old Style)

The oldest formatting method, borrowed from C’s printf:

name = "Alice"
age = 25

print("Hello, %s! You are %d years old." % (name, age))
# Hello, Alice! You are 25 years old.

Common Format Specifiers

Specifier Meaning Example
%s String "Hello, %s" % "World"
%d Integer "Age: %d" % 25
%f Float "Price: %f" % 19.99
%.2f Float (2 decimals) "Price: %.2f" % 19.99
%x Hex "%x" % 255 → "ff"
# Float formatting
pi = 3.14159
print("Pi is approximately %.2f" % pi)
# Pi is approximately 3.14

# Padding
print("%-10s | %5d" % ("Alice", 95))
print("%-10s | %5d" % ("Bob", 87))
# Alice      |    95
# Bob        |    87

Note: The % style is considered legacy. You’ll see it in older code, but prefer f-strings for new code.

Method 2: str.format()

Introduced in Python 2.6, str.format() is more powerful and readable:

name = "Alice"
age = 25

# Positional arguments
print("Hello, {}! You are {} years old.".format(name, age))
# Hello, Alice! You are 25 years old.

# Numbered positions
print("{0} is {1} years old. {0} likes Python.".format(name, age))
# Alice is 25 years old. Alice likes Python.

# Named arguments
print("Hello, {name}! You are {age} years old.".format(name="Alice", age=25))
# Hello, Alice! You are 25 years old.

Formatting with str.format()

# Decimal places
print("Pi: {:.2f}".format(3.14159))
# Pi: 3.14

# Padding and alignment
print("{:<10} | {:>5}".format("Name", "Score"))
print("{:<10} | {:>5}".format("Alice", 95))
print("{:<10} | {:>5}".format("Bob", 87))
# Name       | Score
# Alice      |    95
# Bob        |    87

# Comma separator
print("{:,}".format(1000000))
# 1,000,000

See the dedicated f-Strings page for comprehensive coverage.

name = "Alice"
age = 25
print(f"Hello, {name}! You are {age} years old.")
# Hello, Alice! You are 25 years old.

Method Comparison

Feature % Operator str.format() f-String
Python version All 2.6+ 3.6+
Readability Low Medium High
Speed Fast Slower Fastest
Expressions No Limited Yes
Recommended Legacy OK ✅ Yes
name = "Alice"
score = 95.678

# Same output, three ways:
print("Hello, %s! Score: %.1f" % (name, score))
print("Hello, {}! Score: {:.1f}".format(name, score))
print(f"Hello, {name}! Score: {score:.1f}")
# All produce: Hello, Alice! Score: 95.7

Alignment and Padding

These work with both str.format() and f-strings:

Syntax Meaning Example Result
< Left-align f"{'hi':<10}" "hi "
> Right-align f"{'hi':>10}" " hi"
^ Center f"{'hi':^10}" " hi "
0 Zero-pad f"{42:05}" "00042"
# Building a formatted table
header = f"{'Name':<12} {'Score':>6} {'Grade':^8}"
row1 = f"{'Alice':<12} {95:>6} {'A':^8}"
row2 = f"{'Bob':<12} {87:>6} {'B':^8}"

print(header)
print("-" * len(header))
print(row1)
print(row2)

Output:

Name          Score  Grade
----------------------------
Alice            95    A
Bob              87    B

Summary

  • % operator is the oldest method — use it to read legacy code
  • str.format() is more flexible — useful for reusable templates
  • f-strings are the recommended approach — fastest, most readable
  • All three support alignment, padding, and number formatting
  • Use f-strings for new Python 3.6+ code

Next up: f-Strings →

Updated: