Python F-Strings: Advanced String Interpolation

Learn how to format strings in Python using F-strings. Master expression evaluation, float precision formatting, datetime printing, and self-documenting syntax.

Try Python F-Strings Code

Overview

Formatting strings is a task that developers perform daily. Historically, Python formatting relied on C-style `%` formatting or the `.format()` method. While functional, these older syntax styles often led to verbose, hard-to-read code. Python 3.6 introduced Formatted String Literals, commonly known as F-strings. F-strings provide a concise, readable, and highly optimized syntax for inserting variables and expressions directly into string literals.

To create an F-string, you prefix the string literal with an `f` or `F` (e.g., `f"Hello {name}"`). Any variable or Python expression placed inside curly braces `{...}` is evaluated at runtime and converted to a string automatically. F-strings are not just for variables; you can call functions, perform math calculations, and even access dictionary values inside the curly braces, eliminating the need for temporary variables.

F-strings also feature a rich formatting language. By appending a colon `:` inside the curly braces, you can specify formatting rules. For example, `{value:.2f}` rounds a float to two decimal places, `{num:03d}` pads an integer with leading zeros, and `{date:%Y-%m-%d}` formats a datetime object. In Python 3.8+, F-strings introduced the debugging syntax `{variable=}`, which prints both the variable name and its value automatically, making debugging quick and painless.

Code Example

Demonstrating float formatting, expression evaluation, and self-documenting equal-sign debugging.

fstrings_demo.py
Try in Editor
name = "Charlie"
price = 19.995
quantity = 3

# Basic interpolation and math evaluation
receipt = f"Customer: {name} | Total: ${price * quantity:.2f}"
print(receipt)

# Padding and alignment
number = 42
padded = f"ID: {number:05d}"
print(padded)

# Self-documenting debugging syntax (Python 3.8+)
value = 100
print(f"Debug output: {value=}")
Terminal Output
Customer: Charlie | Total: $59.99
ID: 00042
Debug output: value=100

Real-world Use Cases

  • Prettifying numerical outputs in reports and dashboards
  • Constructing dynamic SQL queries or API request payloads
  • Printing quick debug statements during local testing

Frequently Asked Questions

Are F-strings faster than other string formatting methods?

Yes, F-strings are faster than % formatting and .format() because they are evaluated at runtime as optimized bytecode rather than parsed at execution.

How do I print literal curly braces in an F-string?

You can escape literal curly braces by doubling them, e.g., f"{{Hello}}" will print the literal text '{Hello}'.

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.