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.
:.2f for 2 decimal places).% 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)
{} as placeholders.{0}, {1} to reorder values.f"My name is {name} and I am {age} years old."
f before the opening quote.{} (e.g., {age + 1}).{price:.2f} → 2 decimal places, useful for currency.{text:>10} (right), {text:<10} (left), {text:^10} (center).
# Using old-style % formatting
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
# 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 an f-string for string interpolation
name = "Charlie"
age = 28
print(f"My name is {name} and I am {age} years old.")
price = 49.56789
print("Price: {:.2f}".format(price)) # str.format
print(f"Price: {price:.2f}") # f-string
text = "Hello"
print(f"{text:>10}") # Right aligned
print(f"{text:<10}") # Left aligned
print(f"{text:^10}") # Center aligned
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.
f-strings (Python 3.6+) for clean, readable, and fast string formatting.:.2f or similar specifiers when displaying money or measurements that need fixed precision.<, >, ^) for columns and text-based tables.% and f-strings) in the same project unless necessary.f before an f-string, or Python will treat braces literally.% formatting to print a sentence with your name and age, for example: "My name is ... and I am ... years old."str.format() to display a floating-point number with 3 decimal places.{age + 1} or {price * 0.9}.