Python String Formatting
Python String Formatting
String formatting in Python allows you to embed variables or expressions inside a string in a readable and manageable way. Python provides multiple ways to format strings, and the choice of method often depends on personal preference or the version of Python you’re using.
1. Old-Style String Formatting (% Operator)
The % operator is the older way of formatting strings in Python. It works by using placeholders within a string and replacing them with values.
Syntax:
"string with %s placeholder" % value
Example:
name = "Alice"
age = 25
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)
Output:
Name: Alice, Age: 25
%s: String placeholder.%d: Integer placeholder.
Other common placeholders:
%f: Floating-point number.%x: Hexadecimal number.
2. str.format() Method
Introduced in Python 2.7 and 3.0, the str.format() method provides a more powerful and flexible way to format strings. It allows placeholders within curly braces {} and supports various formatting options.
Syntax:
"string with {} placeholder".format(value)
Example:
name = "Alice"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)
Output:
Name: Alice, Age: 25
You can also specify the order of the values:
formatted_string = "Age: {1}, Name: {0}".format(name, age)
print(formatted_string)
Output:
Age: 25, Name: Alice
Example with Named Placeholders:
formatted_string = "Name: {name}, Age: {age}".format(name="Alice", age=25)
print(formatted_string)
Output:
Name: Alice, Age: 25
3. F-Strings (Literal String Interpolation) — Python 3.6+
F-strings are a more modern and concise way to format strings in Python 3.6 and beyond. F-strings are prefixed with f before the string and allow you to embed expressions directly inside the string using curly braces {}.
Syntax:
f"string with {variable} or {expression}"
Example:
name = "Alice"
age = 25
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)
Output:
Name: Alice, Age: 25
F-strings can also evaluate expressions inside the curly braces:
formatted_string = f"Next year, {name} will be {age + 1} years old."
print(formatted_string)
Output:
Next year, Alice will be 26 years old.
4. String Formatting with Width, Alignment, and Precision
You can specify width, alignment, and precision in string formatting.
Example with Width and Alignment:
name = "Alice"
formatted_string = f"{name:10}" # 10 characters wide, right-aligned by default
print(f"'{formatted_string}'")
Output:
'Alice '
To left-align:
formatted_string = f"{name:<10}" # Left-aligned
print(f"'{formatted_string}'")
Output:
'Alice '
To center-align:
formatted_string = f"{name:^10}" # Center-aligned
print(f"'{formatted_string}'")
Output:
' Alice '
Example with Number Formatting:
pi = 3.14159265359
formatted_string = f"Pi to two decimal places: {pi:.2f}"
print(formatted_string)
Output:
Pi to two decimal places: 3.14
Here, .2f specifies that the number should be formatted with 2 decimal places.
5. % Formatting with Width, Precision, and Alignment
You can also use the % operator for more advanced formatting options, like specifying the width and precision of numbers.
Example:
pi = 3.14159265359
formatted_string = "Pi to 3 decimal places: %.3f" % pi
print(formatted_string)
Output:
Pi to 3 decimal places: 3.142
Comparison of Methods
| Method | Example | Advantages | Disadvantages |
|---|---|---|---|
% Operator | "Hello, %s" % name | Simple and quick for basic formatting | Less flexible, error-prone |
str.format() | "Hello, {}".format(name) | More readable, flexible, supports reordering | Slightly more verbose |
| F-Strings | f"Hello, {name}" | Concise, fast, supports expressions inside {} | Available only in Python 3.6+ |
Summary
%formatting is older and simpler but less flexible.str.format()offers more power and flexibility, including named placeholders and reordering.- F-strings provide the most modern and readable approach, supporting expressions directly in the string.
F-strings are generally preferred in Python 3.6 and later due to their simplicity and speed.