Python String Formatting
String formatting is a crucial aspect of Python programming, allowing you to create dynamic, readable strings that incorporate variable values. This guide will explore various methods of string formatting in Python, from the oldest to the most modern techniques.
1. % Operator (Old Style)
The %
operator is the oldest method of string formatting in Python. While it's still supported, it's generally considered outdated.
name = "Alice"
age = 30
print("My name is %s and I'm %d years old." % (name, age))
# Output: My name is Alice and I'm 30 years old.
Format specifiers:
%s
for strings%d
for integers%f
for floating-point numbers%.2f
for floating-point with fixed precision
price = 19.99
print("The price is $%.2f" % price)
# Output: The price is $19.99
2. str.format() Method
The str.format()
method provides a more versatile way of formatting strings.
name = "Bob"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
# Output: My name is Bob and I'm 25 years old.
You can also use numbered placeholders:
print("The {0} is {1} years old. {0} likes to play {2}.".format("dog", 5, "fetch"))
# Output: The dog is 5 years old. dog likes to play fetch.
Or named placeholders:
print("My name is {name} and I'm {age} years old.".format(name="Charlie", age=35))
# Output: My name is Charlie and I'm 35 years old.
3. f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings provide the most concise and readable way to format strings.
name = "David"
age = 40
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is David and I'm 40 years old.
You can include expressions inside the curly braces:
x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}")
# Output: The sum of 10 and 20 is 30
4. Template Strings
For simple substitutions, you can use the string.Template
class:
from string import Template
name = "Eve"
t = Template("Hey, $name!")
print(t.substitute(name=name))
# Output: Hey, Eve!
Formatting Options
Alignment and Padding
You can specify alignment and padding in your format specifiers:
# Using str.format()
print("|{:<10}|{:>10}|{:^10}|".format("left", "right", "center"))
# Output: |left | right| center |
# Using f-strings
left, right, center = "left", "right", "center"
print(f"|{left:<10}|{right:>10}|{center:^10}|")
# Output: |left | right| center |
Number Formatting
num = 1234.5678
# Using str.format()
print("Number: {:,.2f}".format(num))
# Output: Number: 1,234.57
# Using f-strings
print(f"Number: {num:,.2f}")
# Output: Number: 1,234.57
Date Formatting
from datetime import datetime
now = datetime.now()
# Using str.format()
print("Current date: {:%Y-%m-%d %H:%M:%S}".format(now))
# Using f-strings
print(f"Current date: {now:%Y-%m-%d %H:%M:%S}")
Best Practices
- Use f-strings: For Python 3.6+, f-strings are generally the most readable and efficient option.
- Readability: Choose the formatting method that makes your code most readable.
- Consistency: Stick to one formatting method throughout your project for consistency.
- Avoid hardcoding: Use formatting to separate the structure of your strings from the data they contain.
- Use named placeholders: For complex formatting, named placeholders can improve readability.
Common Pitfalls
- Forgetting to close brackets: Make sure all opening curly braces
{
have a corresponding closing brace}
. - Type mismatches: Ensure the type of your data matches the format specifier you're using.
- Overcomplicating: Sometimes simple concatenation is more readable than complex formatting.
- Performance: While generally negligible, be aware that different formatting methods have slightly different performance characteristics.
Advanced Techniques
Custom Formatting
You can define custom formatting for your objects by implementing the __format__
method:
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __format__(self, format_spec):
if format_spec == "":
return f"({self.x}, {self.y})"
elif format_spec == "polar":
r = (self.x**2 + self.y**2)**0.5
theta = math.atan2(self.y, self.x)
return f"r={r:.2f}, θ={theta:.2f}"
p = Point(3, 4)
print(f"Cartesian: {p}") # Output: Cartesian: (3, 4)
print(f"Polar: {p:polar}") # Output: Polar: r=5.00, θ=0.93
Conclusion
String formatting in Python offers a variety of methods to create dynamic, readable strings. While older methods like %
formatting and str.format()
are still in use, f-strings provide the most concise and often the most readable approach for Python 3.6+. By understanding these different methods and their use cases, you can choose the most appropriate formatting technique for your specific needs, leading to more elegant and maintainable code.