F-Strings
F-Strings
Section titled โF-StringsโWhat it is
Section titled โWhat it isโF-strings (formatted string literals) provide a concise way to embed expressions inside string literals. Introduced in Python 3.6 (2016), they use f prefix and curly braces for interpolation.
Before this feature
Section titled โBefore this featureโString formatting required verbose methods:
# Old % formattingname = "Alice"age = 25message = "Hello, %s! You are %d years old." % (name, age)
# .format() methodmessage = "Hello, {}! You are {} years old.".format(name, age)message = "Hello, {name}! You are {age} years old.".format(name=name, age=age)After this feature
Section titled โAfter this featureโF-strings provide clean, readable syntax:
# F-stringname = "Alice"age = 25message = f"Hello, {name}! You are {age} years old."
# Expressionsx = 10y = 20result = f"The sum of {x} and {y} is {x + y}"
# Method callstext = "python"formatted = f"Language: {text.upper()}"
# Formatting specifiersprice = 19.99formatted_price = f"Price: ${price:.2f}" # "Price: $19.99"
# Multi-line f-stringsuser = {"name": "Bob", "role": "admin"}info = f"""User Information: Name: {user['name']} Role: {user['role']}"""
# Debug feature (Python 3.8+)value = 42debug = f"{value=}" # "value=42"Why this is better
Section titled โWhy this is betterโ- Readable: Expressions directly in string
- Concise: Less verbose than
.format() - Fast: Faster than other formatting methods
- Powerful: Can include any Python expression
- Debugging:
=specifier shows variable name and value
Key notes / edge cases
Section titled โKey notes / edge casesโ- Canโt use backslashes inside
{}(use temp variable) - Can nest f-strings (but readability suffers)
- Raw f-strings:
fr"..."orrf"..." - Evaluated at runtime, not compile time
- Can format numbers, dates, custom objects
# Formatting numbersvalue = 1234567.89formatted = f"{value:,.2f}" # "1,234,567.89"percent = f"{0.875:.1%}" # "87.5%"
# Date formattingfrom datetime import datetimenow = datetime.now()date_str = f"{now:%Y-%m-%d %H:%M:%S}"
# Custom alignmentname = "Alice"aligned = f"|{name:<10}|" # left-alignedaligned = f"|{name:>10}|" # right-alignedaligned = f"|{name:^10}|" # centeredQuick practice
Section titled โQuick practiceโ-
Create an f-string that shows โProduct: Laptop, Price: $999โ
Answer
product = "Laptop"price = 999message = f"Product: {product}, Price: ${price}" -
Format ฯ (3.14159) to 2 decimal places
Answer
import mathformatted = f"{math.pi:.2f}" # "3.14" -
Debug print a variable showing both name and value
Answer
count = 42print(f"{count=}") # Prints: count=42