π¨ Python String Formatting β f-Strings, Format(), and % Explained
π§² Introduction β Why String Formatting Matters
String formatting allows you to insert variables, numbers, and expressions into strings with clarity and control. Itβs essential for generating readable messages, dynamic output, user-friendly logs, and cleanly structured data in Python.
Python supports multiple formatting styles, including:
- f-strings (modern, fast, Python 3.6+)
- str.format()(versatile and widely used)
- %formatting (older but still supported)
π― In this guide, you’ll learn:
- How to format strings using f-strings, format(), and%
- Formatting numbers, dates, and alignment
- When to use each method
- Best practices for readability and maintainability
β³οΈ Method 1: f-Strings (Python 3.6+)
The most modern and readable approach.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
β Supports expressions:
print(f"5 + 3 = {5 + 3}")  # Output: 5 + 3 = 8
π§ Method 2: str.format()
A flexible way to insert values into placeholders {}.
print("Hello, {}!".format("Bob"))
print("My name is {} and I am {}.".format("Alice", 30))
You can also reference by index or keyword:
print("Coordinates: {1}, {0}".format("Y", "X"))
print("Name: {name}, Age: {age}".format(name="Charlie", age=40))
π― Method 3: % Operator (Old Style)
This is an older syntax borrowed from C.
name = "David"
age = 25
print("My name is %s and I am %d years old." % (name, age))
π‘ Still supported, but less readable and flexible than f-strings or .format().
π’ Formatting Numbers
| Task | f-String Example | Output | 
|---|---|---|
| 2 decimal places | f"{3.14159:.2f}" | 3.14 | 
| Comma separator | f"{1000000:,}" | 1,000,000 | 
| Leading zeros | f"{42:05}" | 00042 | 
| Percentage | f"{0.25:.0%}" | 25% | 
π Formatting Dates
With datetime module:
from datetime import datetime
now = datetime.now()
print(f"Today is {now:%Y-%m-%d %H:%M}")
β Output:
Today is 2025-05-13 20:00
π§ String Alignment
You can align text using :> (right), :< (left), and :^ (center):
print(f"{'Name':<10}{'Age':>5}")   # Output: Name         Age
print(f"{'Alice':<10}{30:>5}")     # Output: Alice        30
π‘ Best Practices
- β Use f-strings for readability and performance (Python 3.6+)
- β
 Use .format()when supporting Python 3.5 and below
- β Avoid %unless maintaining legacy code
- β Use formatting for precision, alignment, and dynamic data injection
π Summary β Recap & Next Steps
Python offers multiple ways to format strings for readability, alignment, and data insertion. Mastering these tools helps you create cleaner outputs and more user-friendly applications.
π Key Takeaways:
- β
 Use f-stringsfor modern and expressive formatting.
- β
 Use .format()for backward compatibility.
- β
 Avoid %unless maintaining legacy code.
- β Format numbers, dates, and alignments using rich syntax options.
βοΈ Real-World Relevance:
String formatting is critical in reports, logs, user interfaces, data exports, and template generation in both web and CLI apps.
β FAQ Section β Python String Formatting
β What is the best way to format strings in Python?
β f-strings are recommended for clarity, speed, and inline expression support (Python 3.6+).
β How can I format floating-point numbers to 2 decimal places?
β Use:
value = 3.14159
print(f"{value:.2f}")  # Output: 3.14
β Can I align strings using f-strings?
β
 Yes! Use <, >, or ^ for left, right, and center alignment:
print(f"{'Name':<10}{'Age':>5}")
β Is % formatting still used in Python?
β
 Itβs supported but discouraged in favor of f-strings and .format() for clarity and flexibility.
β How do I include variables inside a string?
β Use curly braces with f-strings:
name = "Alice"
print(f"Hello, {name}!")
Share Now :
