← Back to Chapters

Python String Formatting

? Python String Formatting

⚡ Quick Overview

String formatting in Python lets you insert variables and expressions into text in a clean and readable way. The three main approaches you will see are:

  • % formatting (old style, still used in legacy code).
  • str.format() method (flexible and powerful).
  • f-strings (formatted string literals, recommended in modern Python).

Choosing the right style helps you write output lines that are easy to maintain and format nicely for users.

? Key Concepts

  • Placeholders: Special tokens inside the string that are replaced by values.
  • Format specifiers: Control how numbers, text, and dates appear (e.g. :.2f for 2 decimal places).
  • Alignment & padding: Position text within a fixed width (left, right, center).
  • Readability: Clear formatting makes longer output and tables easier to read.
  • Modern style: Prefer f-strings in Python 3.6+ for most new code.

? Syntax and Theory

  • Old style % formatting:
    "My name is %s and I am %d years old." % (name, age)
    • %s for strings, %d for integers, %f for floats, etc.
  • str.format() method:
    "My name is {} and I am {} years old.".format(name, age)
    • Use {} as placeholders.
    • Can use indexes like {0}, {1} to reorder values.
  • f-strings (formatted string literals):
    f"My name is {name} and I am {age} years old."
    • Write an f before the opening quote.
    • Place expressions directly inside {} (e.g., {age + 1}).
  • Number formatting:
    {price:.2f} → 2 decimal places, useful for currency.
  • Alignment:
    {text:>10} (right), {text:<10} (left), {text:^10} (center).

? Code Examples

? Old Style: % Formatting
# Using old-style % formatting
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
? Using str.format()
# Using str.format() with implicit and explicit indexes
name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
print("My name is {0} and I am {1} years old.".format(name, age))
✨ Using f-Strings (Python 3.6+)
# Using an f-string for string interpolation
name = "Charlie"
age = 28
print(f"My name is {name} and I am {age} years old.")
? Number Formatting with str.format() and f-Strings
price = 49.56789
print("Price: {:.2f}".format(price))   # str.format
print(f"Price: {price:.2f}")           # f-string
? Alignment and Padding
text = "Hello"
print(f"{text:>10}")   # Right aligned
print(f"{text:<10}")   # Left aligned
print(f"{text:^10}")   # Center aligned

? Live Output and Explanation

? Example Output

For the old-style % formatting example:

# Output from the % formatting example
My name is Alice and I am 25 years old.

For the f-string number formatting example:

# Output from the f-string number formatting example
Price: 49.57

Notice how :.2f rounds the number to 2 decimal places. Alignment specifiers like >10 and ^10 help you build neatly formatted tables by placing text within a fixed width.

? Tips and Best Practices

  • Use f-strings (Python 3.6+) for clean, readable, and fast string formatting.
  • Use :.2f or similar specifiers when displaying money or measurements that need fixed precision.
  • Use alignment (<, >, ^) for columns and text-based tables.
  • Avoid mixing different formatting styles (like % and f-strings) in the same project unless necessary.
  • Always remember the f before an f-string, or Python will treat braces literally.

? Try It Yourself

  • Use % formatting to print a sentence with your name and age, for example: "My name is ... and I am ... years old."
  • Use str.format() to display a floating-point number with 3 decimal places.
  • Create a small table using f-strings that shows item names and prices aligned in columns using left, right, and center alignment.
  • Experiment by combining expressions in f-strings, such as {age + 1} or {price * 0.9}.