💡 Advanced Python Concepts
Estimated reading: 3 minutes 261 views

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

MethodSyntax ExampleIntroduced In
f-stringsf"Name: {name}"Python 3.6+
str.format()"Name: {}".format(name)Python 2.6+
% formatting"Name: %s" % nameLegacy

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 tablesPrinting raw, unaligned values
Format currency with :, and .2fShowing more decimal digits than needed
Use descriptive variable namesWriting 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-strings for clarity, performance, and embedded expressions
  • Control alignment, width, precision, and padding easily
  • Use :, for thousands separators and .2f for 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 :
Share

Python Output Formatting

Or Copy Link

CONTENTS
Scroll to Top