Formatted string literals (f-strings) are Python’s most modern, concise, and readable way to embed expressions and variables directly inside string literals — introduced in Python 3.6 and now the dominant method for string formatting in 2026. By prefixing a string with f or F, you can place any valid Python expression inside curly braces {}, and it is evaluated at runtime and formatted into the string. F-strings are faster than .format() and %-style, support format specifiers for alignment/precision/type, allow nested expressions, and eliminate the need for separate argument passing — making them ideal for logging, reporting, templating, user messages, debugging, and data presentation. They also integrate seamlessly with pandas/Polars for vectorized string formatting in large datasets.
Here’s a complete, practical guide to f-strings: basic usage, expressions and calculations, format specifiers, real-world patterns, comparison with older methods, and modern best practices with type hints, safety, performance, and pandas/Polars integration.
Basic f-strings embed variables or simple expressions directly — no .format() call needed.
name = "Alice"
age = 25
occupation = "programmer"
print(f"My name is {name}, I am {age} years old, and I work as a {occupation}.")
# My name is Alice, I am 25 years old, and I work as a programmer.
Expressions, calculations, and function calls are evaluated inline — f-strings support full Python expressions inside braces.
price = 19.99
quantity = 3
print(f"Total cost: ${price * quantity:.2f}") # Total cost: $59.97
print(f"Next birthday in {365 - 100} days") # Next birthday in 265 days
print(f"Uppercase name: {name.upper()}") # Uppercase name: ALICE
print(f"Date: {date.today():%Y-%m-%d}") # Date: 2026-02-10
Format specifiers inside braces control alignment, padding, precision, and type — same syntax as .format().
print(f"Price: ${price:>10.2f}") # Price: $ 19.99 (right-aligned, width 10)
print(f"Tax rate: {0.0875:.1%}") # Tax rate: 8.8%
print(f"ID: {42:05d}") # ID: 00042 (zero-padded to 5 digits)
print(f"Name: {name:<10} Age: {age:>3}") # Name: Alice Age: 25
print(f"Scientific: {123456:.2e}") # Scientific: 1.23e+05
Real-world pattern: dynamic logging, reports, templating, and data display — f-strings are ideal for inline formatting in scripts and vectorized pandas/Polars output.
# Log message
level = "INFO"
message = "User login successful"
print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] {level}: {message}")
# [2026-02-10 14:30:45] INFO: User login successful
# pandas vectorized f-string formatting (via apply or list comprehension)
import pandas as pd
df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
df['greeting'] = df.apply(lambda row: f"Hello {row['name']}, you are {row['age']}!", axis=1)
print(df)
# name age greeting
# 0 Alice 25 Hello Alice, you are 25!
# 1 Bob 30 Hello Bob, you are 30!
Best practices make f-string usage safe, readable, and performant. Prefer f-strings for all new code — fastest, clearest, support expressions, and least error-prone. Use .format() only when format string is dynamic (from file, config, database) — template.format_map(data_dict). Modern tip: use Polars for large string formatting — pl.col("name").str.format("Hello {}") is fast and vectorized. Add type hints — str — improves static analysis. Use nested f-strings or expressions — f"Total: {price * quantity:.2f}" — but keep complex logic outside for readability. Handle edge cases — f-strings raise errors on invalid expressions; wrap in try/except for user input. For localization/internationalization, use gettext with f-strings or .format(). Avoid legacy % — deprecated in favor of f-strings and .format(). Combine with str.join() — ", ".join(f"{x:.2f}" for x in values) formats lists cleanly.
f-strings are Python’s cleanest, fastest, and most readable string formatting method — embed variables and expressions directly with full specifier support. In 2026, use f-strings everywhere possible, .format() for dynamic templates, vectorize in pandas/Polars, and add type hints for safety. Master f-strings, and you’ll create dynamic, formatted output for logs, reports, templates, and user messages with elegance and efficiency.
Next time you need to insert values into a string — reach for f-strings. It’s Python’s cleanest way to say: “Put this value here, formatted exactly right.”