๐จ๏ธ Python Output Formatting โ f-Strings, Alignment, and Precision
๐งฒ Introduction โ Why Format Output in Python?
Whether you’re writing logs, reports, tables, or dynamic UI elements, how your output appears matters. Python offers multiple ways to format output cleanly and precisely, ensuring itโs:
- โจ Readable
- ๐ Aligned
- ๐ฏ Accurate (especially for floats, currency, etc.)
From old-school %-formatting to modern f-strings, Python gives you powerful, flexible formatting tools.
๐ฏ In this guide, youโll learn:
- Basic and advanced string formatting techniques
- Aligning text, padding numbers, and setting decimal precision
- Real-world formatting examples (currency, dates, tables)
- Best practices for clean output
โ Methods for Formatting Strings
| Method | Syntax Example | Introduced In |
|---|---|---|
f-strings | f"Name: {name}" | Python 3.6+ |
str.format() | "Name: {}".format(name) | Python 2.6+ |
% formatting | "Name: %s" % name | Legacy |
๐งฉ 1. f-strings โ Modern and Recommended
name = "Alice"
score = 95.6789
print(f"Student: {name}, Score: {score:.2f}")
# Output: Student: Alice, Score: 95.68
โ Supports embedded expressions and precision control.
๐งฑ 2. str.format() Method
print("Name: {}, Age: {}".format("Bob", 30))
print("Price: {:.2f}".format(99.999))
โ Still widely used, especially for older Python code.
๐ 3. % Formatting โ Old Style
name = "Charlie"
print("Name: %s" % name)
print("Value: %.2f" % 3.14159)
โ ๏ธ Less readable and flexibleโavoid in new code.
๐ง Alignment, Padding, and Width
โ Align Text
name = "Eve"
print(f"|{name:<10}|") # Left-aligned
print(f"|{name:^10}|") # Centered
print(f"|{name:>10}|") # Right-aligned
โ Output:
|Eve |
| Eve |
| Eve|
โ Pad Numbers with Zeroes
num = 42
print(f"{num:05}") # 00042
๐ Floating Point Precision
pi = 3.14159265
print(f"Rounded: {pi:.2f}") # Rounded: 3.14
๐ต Format Currency and Commas
price = 1234567.8910
print(f"${price:,.2f}") # $1,234,567.89
โ Adds commas and limits to two decimalsโperfect for financial data.
๐ Format Dates and Times
from datetime import datetime
now = datetime.now()
print(f"Today: {now:%Y-%m-%d %H:%M}")
# Output: Today: 2025-05-15 16:45
๐งฎ Tabular Output โ Format Tables in Loops
data = [("Alice", 90), ("Bob", 85), ("Charlie", 92)]
for name, score in data:
print(f"{name:<10} | {score:>5}")
โ Output:
Alice | 90
Bob | 85
Charlie | 92
๐ Format Nested Expressions
discount = 0.15
price = 250
print(f"Final price: ${price * (1 - discount):.2f}")
โ
Output: Final price: $212.50
๐ฏ Format with Dictionaries and Named Fields
user = {"name": "Dana", "score": 88}
print("User: {name}, Score: {score}".format(**user))
โ Great for template-based rendering.
๐ Best Practices
| โ Do This | โ Avoid This |
|---|---|
Use f-strings (Python 3.6+) | Mixing % with format() or f-string |
| Use alignment and precision for tables | Printing raw, unaligned values |
Format currency with :, and .2f | Showing more decimal digits than needed |
| Use descriptive variable names | Writing unreadable f-strings |
๐ Summary โ Recap & Next Steps
Python gives you powerful formatting tools to generate clear, polished output. Whether you’re writing CLI reports, data dashboards, or logging frameworks, mastering formatting makes your output more professional and useful.
๐ Key Takeaways:
- โ
Use
f-stringsfor clarity, performance, and embedded expressions - โ Control alignment, width, precision, and padding easily
- โ
Use
:,for thousands separators and.2ffor decimal rounding - โ Great for reports, tables, logs, and UI output
โ๏ธ Real-World Relevance:
Used in command-line tools, automated reports, data visualization, web responses, and debugging tools.
โ FAQ โ Python Output Formatting
โ Whatโs the best way to format output in Python?
โ
Use f-strings (Python 3.6+) for most use casesโthey are fast, readable, and powerful.
โ How do I round floats to two decimal places?
โ Use:
f"{value:.2f}"
โ How do I align text output in Python?
โ
Use <, >, or ^ inside format specifiers:
f"{text:>10}" # Right-align
โ Can I format numbers with commas?
โ
Yes. Use :, inside your format string:
f"{number:,}"
โ Are f-strings faster than .format()?
โ Yes. F-strings are faster and more concise.
Share Now :
