Formatted String Literals (f-strings) in Python

Regular Expressions Mar 20, 2026

Formatted String Literals (f-strings) in Python

Formatted string literals, commonly known as f-strings, are the most modern, readable, and performant way to embed variables and expressions inside strings in Python. Introduced in Python 3.6, f-strings have become the standard for data science in 2026 because they are fast, concise, and support powerful formatting specifiers directly inside the string.

TL;DR — Why f-strings Are Preferred in 2026

  • Fastest string formatting method
  • Most readable (variables appear directly inside the string)
  • Supports expressions, format specifiers, and even function calls
  • Ideal for logs, reports, SQL queries, feature names, and dynamic text

1. Basic f-string Syntax

name = "Alice"
score = 95.75
model = "random_forest"

message = f"User {name} achieved {score:.2f}% accuracy with {model} model"
print(message)

# With expressions
total = 1250.75
print(f"Total sales: ${total:,.2f}")

2. Advanced f-string Features

# Format specifiers
print(f"Score: {score:>8.2f}")      # right-aligned, 2 decimals
print(f"Large number: {1234567:,.0f}")  # thousand separators

# Expressions and function calls
data = [10, 20, 30]
print(f"Average: {sum(data)/len(data):.2f}")

# Date formatting inside f-strings
from datetime import date
d = date(2026, 3, 20)
print(f"Report date: {d:%A, %B %d, %Y}")

3. Real-World Data Science Examples

import pandas as pd

# Demo file so this example runs as-is (in your project this is your real results file)
pd.DataFrame({
    "model_name": ["XGBoost", "RandomForest", "LogReg"],
    "accuracy": [92.5, 89.123, 84.3],
    "dataset": ["customer_churn", "fraud", "customer_churn"],
}).to_csv("model_results.csv", index=False)

df = pd.read_csv("model_results.csv")

# Example 1: Dynamic log messages
for row in df.itertuples():
    log = f"Model {row.model_name} achieved {row.accuracy:.2f}% on {row.dataset}"
    print(log)

# Example 2: Build feature names dynamically
prefix = "feature_"
features = ["amount", "quantity", "profit"]
full_features = [f"{prefix}{f}" for f in features]

# Example 3: SQL query construction
columns = ["customer_id", "order_date", "amount"]
query = f"SELECT {', '.join(columns)} FROM sales WHERE amount > 1000"

4. Best Practices in 2026

  • Use f-strings for almost all string formatting tasks
  • Keep complex logic outside the f-string when readability matters
  • Use format specifiers (:.2f, :,, :^10) for clean output
  • Define common templates as constants when they are reused
  • Combine with Regular Expressions when building dynamic patterns

What Makes f-Strings Practical

An f-string evaluates expressions inside braces when the line runs, so you can call methods, do arithmetic and apply format specifications in one place. Since Python 3.8, adding = after an expression, as in f"{total=}", prints both the expression and its value, which is very useful for debugging.

Since Python 3.12, f-strings can reuse the same type of quotes inside the braces, but keeping different quotes remains more readable and works in older versions.

Keep expressions short. Complex logic inside braces makes code hard to read; compute the value first and format it afterwards.

Worked Example: Debugging and Formatting in One Line

We print a summary with the self-documenting = form.

prices = [19.99, 5.25, 12.0]
total = sum(prices)
count = len(prices)

print(f"{total=:.2f}")
print(f"{count=}")
print(f"Average: {total / count:.2f} over {count} items")
name = "pyinns"
print(f"{name.upper()!r}")

The = form shows the variable name with its value, and format specifications still apply after it. The !r conversion shows the string with quotes, which makes spaces and empty strings visible.

Practical Tips

Use f-strings for messages and reports, but use parameterised queries for SQL and string.Template for user-editable text. Each tool has its own safe use, and f-strings evaluate immediately, so they cannot be stored and filled later.

When debugging, the {name=} form is a quick way to print several values with labels in one line.

Keep format specifications after the colon, as in {total:,.2f}, rather than rounding the value first.

Common Mistakes

  • Putting long logic inside braces.
  • Using f-strings for templates that should be filled later.
  • Forgetting the f prefix, which prints the braces literally.
  • Building SQL queries with f-strings instead of parameters.

Quick Summary

  • f-strings evaluate expressions at runtime.
  • {x=} helps with debugging.
  • !r shows the exact value.
  • Keep expressions simple.

Conclusion

Formatted string literals (f-strings) are the modern standard for string formatting in Python. In 2026 data science projects, f-strings make your code cleaner, faster, and more readable than older methods like .format() or the % operator. Mastering f-strings prepares you perfectly for building dynamic strings, logs, reports, and complex Regular Expression patterns.

Next steps:

  • Review your current string-building code and convert it to modern f-strings for improved readability and performance

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices