Skip to main content Brad's PyNotes

PEP 498: F-Strings - The Modern Way to Format Python Strings

TL;DR

PEP 498 introduced f-strings (formatted string literals) in Python 3.6, allowing direct expression embedding in strings with f"Hello {name}" syntax, making string formatting more readable and performant.

Interesting!

F-strings are faster than .format() and % formatting because they’re evaluated at compile time rather than requiring method calls at runtime.

The String Formatting Revolution

PEP 498 transformed how Python developers work with strings by introducing f-strings for clean, efficient expression embedding.

Expression Power Inside F-Strings

Direct Calculations

python code snippet start

radius = 5
area = f"Circle area: {3.14159 * radius ** 2:.2f}"
print(area)  # Circle area: 78.54

import math
precise = f"Precise: {math.pi * radius ** 2:.4f}"
print(precise)  # Precise: 78.5398

python code snippet end

Object Methods

python code snippet start

from datetime import datetime

class Person:
    def __init__(self, name, birth_year):
        self.name = name
        self.birth_year = birth_year
    
    def get_age(self):
        return datetime.now().year - self.birth_year

alice = Person("Alice", 1990)
message = f"{alice.name} is {alice.get_age()} years old"

python code snippet end

Powerful Formatting Options

Number Formatting

python code snippet start

value = 1234.5678
print(f"Default: {value}")           # 1234.5678
print(f"Two decimals: {value:.2f}")  # 1234.57
print(f"Comma separator: {value:,}") # 1,234.5678
print(f"Percentage: {value:.2%}")    # 123456.78%

python code snippet end

Debugging (Python 3.8+)

python code snippet start

user_id = 12345
username = "alice"
print(f"{user_id=}, {username=}")
# Output: user_id=12345, username='alice'

python code snippet end

F-strings represent Python’s commitment to readable, efficient code by eliminating the disconnect between format strings and their data.

F-strings work beautifully with string module utilities and are featured prominently in Python's I/O operations for modern text formatting.

Reference: PEP 498 - Literal String Interpolation