πŸ“š Python Strings & Text Manipulation
Estimated reading: 3 minutes 36 views

🎨 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

Taskf-String ExampleOutput
2 decimal placesf"{3.14159:.2f}"3.14
Comma separatorf"{1000000:,}"1,000,000
Leading zerosf"{42:05}"00042
Percentagef"{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-strings for 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python String Formatting

Or Copy Link

CONTENTS
Scroll to Top