F-String Formatting in Python
F-strings (formatted string literals) provide a concise, readable way to embed expressions inside strings. They're faster and cleaner than .format() or % formatting.
Basic Usage
name = "Alice"
age = 30
# Old way
print("Hello, " + name + ". You are " + str(age))
# f-string way (Python 3.6+)
print(f"Hello, {name}. You are {age}")
# Output: Hello, Alice. You are 30
Expressions Inside F-Strings
a = 5
b = 10
print(f"Sum: {a + b}, Product: {a * b}")
# Output: Sum: 15, Product: 50
# Method calls
name = "alice"
print(f"Uppercase: {name.upper()}")
# Output: Uppercase: ALICE
# Conditional expressions
score = 85
print(f"Result: {'Pass' if score >= 60 else 'Fail'}")
# Output: Result: Pass
Number Formatting
# Decimal places
pi = 3.14159265359
print(f"Pi: {pi:.2f}") # Output: Pi: 3.14
print(f"Pi: {pi:.4f}") # Output: Pi: 3.1416
# Comma separator for thousands
big_number = 1234567
print(f"Amount: {big_number:,}") # Output: Amount: 1,234,567
# Percentage
ratio = 0.857
print(f"Success rate: {ratio:.1%}") # Output: Success rate: 85.7%
# Scientific notation
tiny = 0.000001234
print(f"Value: {tiny:.2e}") # Output: Value: 1.23e-06
Alignment and Padding
# Right align (10 characters wide)
print(f"{'right':>10}") # Output: right
# Left align
print(f"{'left':<10}") # Output: left
# Center
print(f"{'center':^10}") # Output: center
# Padding with zeros
number = 42
print(f"{number:05}") # Output: 00042
Dates and Times
from datetime import datetime
now = datetime.now()
print(f"Date: {now:%Y-%m-%d}") # Output: Date: 2024-03-15
print(f"Time: {now:%H:%M:%S}") # Output: Time: 14:30:45
print(f"Full: {now:%B %d, %Y}") # Output: Full: March 15, 2024
Debugging with f-strings (Python 3.8+)
x = 10
y = 20
# The = operator shows variable name and value
print(f"{x=}, {y=}, {x+y=}")
# Output: x=10, y=20, x+y=30
Multiline F-Strings
name = "Alice"
items = 5
total = 99.99
message = f"""
Order Summary for {name}:
Items: {items}
Total: ${total:.2f}
"""
print(message)
Pro Tip: F-strings are evaluated at runtime and are the fastest string formatting method in Python. Use {variable=} for quick debugging to see both the variable name and its value.
← Back to Python Tips