Also known as: formatted string literal
An f-string (formatted string literal) is a string prefixed with f or F that can contain Python expressions inside curly braces ({}). The expressions are evaluated at runtime and their results are inserted into the string. Introduced in PEP 498 (Python 3.6), f-strings are the most readable and performant way to embed values in strings: f"Hello, {name}!" is clearer than "Hello, {}!".format(name) or "Hello, %s!" % name.
F-strings support format specifications after a colon: f"{price:.2f}" (two decimal places), f"{name:>20}" (right-aligned in 20 characters), f"{count:,}" (thousands separator), f"{value:#x}" (hex with prefix). Since Python 3.8, f"{expr=}" prints both the expression and its value — extremely useful for debugging: f"{x=}" outputs x=42.
F-strings can contain any valid Python expression: function calls, method calls, conditional expressions, dictionary lookups, and even nested f-strings (since Python 3.12, which removed restrictions on backslashes and comments inside f-string braces). They are compiled into efficient string concatenation at bytecode level, making them faster than .format() and % formatting in most cases.
Related terms: String
Discussed in:
- Chapter 7: Strings and Text Processing — String Formatting with f-strings