Python String Formatting: f-Strings and format() Explained | Python tutorials on BeingSkilled

When writing Python programs, you often need to include variables or expressions inside strings. Python provides two modern and readable ways to do this: f-strings (formatted string literals) and the format() method.

This tutorial explores both methods in detail with practical examples to help you decide when and how to use each.

1. What Are f-Strings?

f-Strings (introduced in Python 3.6) allow you to embed expressions directly inside string literals using curly braces {}, prefixed with the letter f.

Example 1: Basic f-string

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.

Example 2: Using expressions inside f-strings

price = 49.99
quantity = 3
print(f"Total: ${price * quantity:.2f}")
# Output: Total: $149.97

Example 3: Embedding function calls

def greet(name):
    return f"Hello, {name}!"

print(f"{greet('Bob')} How are you?")
# Output: Hello, Bob! How are you?

2. What Is format() Method?

The format() method was introduced in Python 2.6 and is still widely used. It uses curly braces {} as placeholders in the string, which get replaced by arguments passed to format().

Example 1: Positional formatting

print("Hello, {}. You are {} years old.".format("Bob", 25))
# Output: Hello, Bob. You are 25 years old.

Example 2: Named placeholders

print("Name: {name}, Age: {age}".format(name="Alice", age=30))
# Output: Name: Alice, Age: 30

Example 3: Index-based formatting

print("First: {0}, Second: {1}, Again First: {0}".format("A", "B"))
# Output: First: A, Second: B, Again First: A

3. Comparing f-Strings vs format()

Feature f-Strings format() Method
Python Version 3.6+ 2.6+
Readability More readable Less readable for long strings
Supports expressions Yes No
Performance Faster Slightly slower

4. Real-World Examples

f-String Example: Logging with timestamps

from datetime import datetime
user = "admin"
print(f"[{datetime.now()}] User '{user}' logged in.")
# Output: [2025-07-13 12:00:00] User 'admin' logged in.

format() Example: Template messages

template = "Dear {name}, your score is {score:.1f}."
message = template.format(name="John", score=92.5)
print(message)
# Output: Dear John, your score is 92.5.

5. Formatting Numbers

f-String with decimal places

pi = 3.14159265
print(f"Pi rounded to 2 decimals: {pi:.2f}")
# Output: Pi rounded to 2 decimals: 3.14

format() with alignment

print("{:<10} {:>5}".format("Item", "Qty"))
print("{:<10} {:>5}".format("Apples", 3))
# Output:
# Item          Qty
# Apples          3

6. Final Thoughts

Both f-strings and format() are excellent tools for string formatting in Python. Use f-strings for most modern code due to their simplicity and speed. However, if you're maintaining older code or working with templates, format() still has its place.

By mastering both, you’ll be well-equipped to handle any string formatting task in your Python projects.