String Formatting in Python
String formatting allows you to insert values into a string in a clean and readable way. Python provides several ways to format strings, and each method has its advantages. Here are the most commonly used string formatting techniques:
1. Old-Style String Formatting (%
operator)
The old-style string formatting uses the %
operator to interpolate values into a string. This method is similar to formatting in the C programming language.
Syntax:
"string" % values
%s
: String format specifier.%d
: Integer format specifier.%f
: Floating-point format specifier.%x
: Hexadecimal format specifier.
Example 1: Old-Style String Formatting
name = "Alice"
age = 30
height = 5.7
# Formatting a string with multiple variables
formatted_string = "My name is %s, I am %d years old and %.1f feet tall." % (name, age, height)
print(formatted_string)
# Output: My name is Alice, I am 30 years old and 5.7 feet tall.
- Advantages: Simple for basic formatting.
- Limitations: Less readable and harder to extend for more complex formatting (like dictionaries).
2. str.format()
Method
The str.format()
method provides more flexibility and readability than the old-style formatting. You can use placeholders in curly braces {}
and pass the variables to format()
.
Syntax:
"string {}".format(value)
You can also specify the index or keyword for positional arguments.
Example 2: str.format()
name = "Alice"
age = 30
height = 5.7
# Basic formatting
formatted_string = "My name is {}, I am {} years old and {:.1f} feet tall.".format(name, age, height)
print(formatted_string)
# Output: My name is Alice, I am 30 years old and 5.7 feet tall.
# Positional arguments
formatted_string2 = "My name is {0}, I am {1} years old, and I am {2} feet tall. {0} is my name.".format(name, age, height)
print(formatted_string2)
# Output: My name is Alice, I am 30 years old, and I am 5.7 feet tall. Alice is my name.
# Keyword arguments
formatted_string3 = "My name is {name}, I am {age} years old and {height} feet tall.".format(name=name, age=age, height=height)
print(formatted_string3)
# Output: My name is Alice, I am 30 years old and 5.7 feet tall.
- Advantages:
- More readable and flexible.
- Supports both positional and keyword arguments.
- Can format values with custom specifications like floating-point precision (
{:.1f}
).
3. F-Strings (Literal String Interpolation) - Python 3.6+
F-strings, or formatted string literals, were introduced in Python 3.6 and are currently the most efficient and readable way to format strings. You can embed expressions directly inside string literals, prefixed with an f
.
Syntax:
f"string {expression}"
Example 3: F-Strings
name = "Alice"
age = 30
height = 5.7
# Basic formatting with f-strings
formatted_string = f"My name is {name}, I am {age} years old and {height:.1f} feet tall."
print(formatted_string)
# Output: My name is Alice, I am 30 years old and 5.7 feet tall.
# Expressions inside f-strings
formatted_string2 = f"My age next year will be {age + 1}."
print(formatted_string2)
# Output: My age next year will be 31.
- Advantages:
- Very readable and concise.
- Allows embedding of expressions directly in the string.
- Best performance, as it’s evaluated at runtime.
4. String Template Class (string.Template
)
The string.Template
class provides a simple way to do string substitution, particularly useful when working with user input, or in cases where security is a concern.
Syntax:
from string import Template
template = Template("string $variable")
formatted_string = template.substitute(variable=value)
Example 4: string.Template
from string import Template
name = "Alice"
age = 30
template = Template("My name is $name and I am $age years old.")
formatted_string = template.substitute(name=name, age=age)
print(formatted_string)
# Output: My name is Alice and I am 30 years old.
- Advantages:
- Simple syntax for substitution.
- Handles missing values more gracefully with
safe_substitute()
.
- Limitations:
- Less flexible than
str.format()
or f-strings.
- Less flexible than
5. Comparison of Different Methods
Feature | % Operator |
str.format() |
F-Strings | string.Template |
---|---|---|---|---|
Readability | Less readable | More readable | Most readable | Simple, but limited |
Flexibility | Limited | More flexible (positional, keyword) | Very flexible, supports expressions | Limited functionality (simple variable substitution) |
Performance | Slower | Slower than f-strings | Fastest | Slower due to additional processing |
Python Version Support | Works in Python 2 and 3 | Works in Python 2 and 3 | Python 3.6+ only | Works in Python 2 and 3 |
Error Handling | Can raise errors | More error messages | Raises NameError if variable is missing |
Provides safe_substitute() to handle missing variables gracefully |
6. Advanced Formatting Techniques
1. Aligning Text
You can align text within a certain width using <
(left-aligned), >
(right-aligned), or ^
(center-aligned).
name = "Alice"
formatted_string = f"|{name:<10}|{name:^10}|{name:>10}|"
print(formatted_string)
# Output: |Alice | Alice | Alice|
2. Padding Numbers with Zeros
You can pad numbers with leading zeros using 0
in formatting.
number = 42
formatted_string = f"Number: {number:05}"
print(formatted_string) # Output: Number: 00042
3. Specifying Floating-Point Precision
Control the number of decimal places using .nf
, where n
is the number of digits.
pi = 3.14159
formatted_string = f"Pi to 3 decimal places: {pi:.3f}"
print(formatted_string) # Output: Pi to 3 decimal places: 3.142
4. Formatting with Thousands Separator
You can format numbers with a thousands separator (commas) using the ,
specifier.
large_number = 1000000
formatted_string = f"Formatted number: {large_number:,}"
print(formatted_string) # Output: Formatted number: 1,000,000
7. Summary of String Formatting Methods
- Old-Style (
%
operator): Simple but less flexible, and harder to maintain. str.format()
: More flexible and readable; supports positional and keyword arguments.- F-Strings: Best for readability and performance; available in Python 3.6+.
string.Template
: Simplest for variable substitution, with some limitations and added safety for user inputs.
F-strings are generally the preferred choice for most modern Python code because of their readability and performance. However, str.format()
remains useful for cases where more complex formatting is required, and string.Template
is useful in specific situations, particularly when working with external input.