Why Use String Formatting?
Instead of manually concatenating strings using operators like +
, string formatting offers a more flexible and readable way to handle dynamic strings. It simplifies the process of inserting values into text while ensuring proper alignment, spacing and formatting.
Methods of String Formatting in Python
Python provides multiple methods for string formatting, each suitable for different use cases:
- Using % Operator (Old Style Formatting)
- Using str.format() Method
- Using f-Strings (String Interpolation)
- Template Strings (from the string module)
1. Using % Operator
The % operator is the oldest way to format strings in Python. It works similarly to placeholders in languages like C.
Syntax:
"string % values"
Example:
name = "Alice"
age = 25
print("My name is %s, and I am %d years old." % (name, age))
Output:
My name is Alice, and I am 25 years old.
Common Placeholders:
- %s – String
- %d – Integer
- %f – Floating-point number
- %.2f – Floating-point with 2 decimal places
Limitations:
- Less readable for complex strings
- Does not support type safety or modern features
2. Using str.format() Method
The str.format() method is more versatile and modern than the % operator. It allows you to use placeholders defined by curly braces { }.
Syntax:
"string {}".format(values)
Example:
name = "Bob"
age = 30
print("My name is {}, and I am {} years old.".format(name, age))
Output:
My name is Bob, and I am 30 years old.
Positional and Keyword Arguments:
You can specify the position or name of placeholders for more control.
print("Hello, {0}. You are {1} years old.".format("Charlie", 22))
print("Hello, {name}. You are {age} years old.".format(name="Diana", age=28))
Formatting Numbers:
price = 49.99
print("The price is {:.2f} dollars.".format(price)) # Two decimal places
Output:
The price is 49.99 dollars.
3. Using f-Strings (String Interpolation)
Introduced in Python 3.6, f-strings are the most modern and recommended way to format strings. They allow you to embed expressions directly within string literals, providing both readability and efficiency.
Syntax:
f"string {expression}"
Example:
name = "Eve"
age = 35
print(f"My name is {name}, and I am {age} years old.")
Output:
My name is Eve, and I am 35 years old.
Inline Expressions:
You can include calculations or function calls inside f-strings.
radius = 5
print(f"The area of the circle is {3.14 * radius ** 2}.")
Output:
The area of the circle is 78.5.
Formatting Numbers:
value = 12345.6789
print(f"The value is {value:.2f}.") # Two decimal places
Output:
The value is 12345.68.
4. Template Strings (from string Module)
The Template class in the string module provides a safe and straightforward way to perform string substitution, especially useful for untrusted input.
Syntax:
from string import Template
template = Template("Hello, $name!")
result = template.substitute(name="Frank")
print(result)
Output:
Hello, Frank!
Safe Substitution:
You can use safe_substitute() to handle missing placeholders gracefully.
template = Template("Hello, $name!")
result = template.safe_substitute()
print(result)
Comparison of String Formatting Methods
Method | Features | Use Case |
---|---|---|
% Operator | Old style, concise but less flexible | Simple strings |
str.format() | Versatile and supports complex formatting | Compatibility with older Python versions |
f-Strings | Modern, efficient and most readable | Recommended for all Python 3.6+ projects |
Template Strings | Safe substitution for untrusted input | Applications needing security |
Advanced String Formatting Techniques
Aligning Text:
print(f"{'Python':<10}") # Left-align
print(f"{'Python':>10}") # Right-align
print(f"{'Python':^10}") # Center-align
Output:
Python
Python
Python
Padding Numbers:
number = 42
print(f"{number:05}") # Pads with zeros to make the number 5 digits
Output:
00042
Real-World Application of String Formatting
Generating Reports: Dynamically create structured reports by embedding variables into string templates.
name = "Alice"
score = 95
print(f"Student: {name}\nScore: {score}")
Building URLs:
base_url = "https://example.com/"
endpoint = "api/v1/resource"
print(f"{base_url}{endpoint}")
Formatting Logs:
user = "Bob"
action = "login"
print(f"User {user} performed {action}.")