f-string

In Python, an f-string—short for formatted string literal—is a useful feature that allows you to interpolate expressions inside string literals, using curly braces {}, to produce a formatted string.

An f-string is prefixed with an f or F. In this type of string literal, you can include Python expressions, which are evaluated and formatted at runtime. F-strings support advanced formatting options, making them a popular choice for Python developers.

Example

Here’s an example of using f-strings to embed variables and expressions within a string:

Python
>>> quantity = 6
>>> item = "bananas"
>>> price = 1.74

>>> f"{quantity} {item} cost ${price * quantity:.2f}"
'6 bananas cost $10.44'

In this example, you interpolate variables and expressions in an f-string using replacement fields delimited by curly braces. The expressions that you embed in an f-string can be almost arbitrarily complex. The examples also show how to use format specifiers in f-string to format currency values.

Tutorial

Python's F-String for String Interpolation and Formatting

Python's f-strings provide a readable way to interpolate and format strings. They're readable, concise, and less prone to error than traditional string interpolation and formatting tools, such as the .format() method and the modulo operator (%). F-strings are also faster than those tools!

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 14, 2025 • Reviewed by Dan Bader