f-string in Python Explained

By
Marko Aleksic
Published:
May 14, 2026
Topics:

Programming in Python frequently requires joining strings with dynamic data. Older methods like modulo operator (%) formatting and .format() served this purpose until Python 3.6 introduced literal string interpolation.

This article explores the mechanics, syntax, and practical applications of f-strings in Python.

f-string in Python explained.

What Are Python f-strings?

An f-string, or formatted string literal, represents a string prefixed with f or F. These strings contain replacement fields surrounded by curly braces ({}) that Python evaluates at runtime.

f-strings are stored as literals rather than function calls. This design allows the Python interpreter to optimize string construction, making f-strings the fastest string formatting method.

Python f-string Uses

Developers use f-strings to inject variables, expressions, and function calls directly into string literals. This capability eliminates the need for complex string concatenation or positional arguments present in the .format() method.

Common f-string use cases include:

  • Logging and debugging. Inserting state variables into log messages for clarity.
  • Data reporting. Formatting numerical output, such as currency or percentages, for end-user displays.
  • Dynamic queries. Constructing SQL queries or API endpoints where parameters change based on logic.
  • UI text. Generating user-facing messages that incorporate names, dates, or specific counts.

Python f-string Syntax

The syntax for an f-string requires a prefix and a set of delimiters. One initiates the string with the letter f followed by single, double, or triple quotes.

Inside the quotes, any text placed within ({}) undergoes evaluation. Python treats the content of the braces as an expression, executes it, and converts the result into a string. The syntax also supports a format specifier, which follows a colon (:) inside the braces to control padding, alignment, and precision.

The table below presents components of an f-string:

ComponentDescriptionExample
PrefixThe character f or F before the opening quote.f"…"
ExpressionThe variable or logic inside the braces.{name}
Format SpecifierOptional instructions for data presentation.{price:.2f}
Literal TextStandard characters outside the braces.f"Total: {total}"

The example below illustrates the syntax. The format specifier rounds the number to zero decimal places:

name = "Alice"
score = 95.5

message = f"Hello {name}, your final score is {score:.0f}%."

print(message)

The output shows a formatted message.

The output of the example code.

Python f-string Examples

Practical examples demonstrate the versatility of f-strings across different data types. These snippets show how the interpreter handles various inputs to produce a single string.

The following sections break down specific scenarios, from simple variable insertion to complex expression evaluation.

Print Date Using f-string

Dates require specific formatting to remain legible for humans. Python’s datetime objects integrate seamlessly with f-string format specifiers.

The f-string uses the (%) directives common in the strftime method. This approach keeps the formatting logic inside the string itself, which reduces code length and improves readability, as in the example below:

from datetime import datetime

now = datetime.now()
print(f"Current date and time: {now:%Y-%m-%d %H:%M:%S}")

The output shows a formatted date and time message.

A formatted date and time message.

Print Variables Using f-string

Variable interpolation is the most common task for f-strings. This method replaces the variable name with its stored value during execution:

name = "Alice"
age = 30
print(f"User {name} is {age} years old.")

The interpreter looks up name and age in the local or global scope. It then places those values into the final string output without requiring explicit type conversion from integer to string.

Using Quotation Marks in f-string

Handling quotation marks inside a string requires paying attention to delimiters. Ensure the internal quotes do not prematurely terminate the f-string itself.

For example:

title = "Python Expert"
print(f"He is known as '{title}' in the community.")
print(f'She said, "f-strings are efficient."')

If the f-string uses double quotes, use single quotes for internal text. Conversely, if the f-string uses single quotes, use double quotes internally. For complex strings containing both, triple quotes (f"""…""") provide the necessary flexibility.

Evaluate Expressions with f-Strings

f-strings can also execute Python code. This allows for arithmetic, method calls, and logic checks within the string literal.

In the example below, the expression {width * height} calculates the product before the string construction completes. This inline evaluation prevents the creation of temporary variables that only serve a single display purpose.

width = 10
height = 5
print(f"The area of the rectangle is {width * height} square units.")
print(f"The name in uppercase is {'python'.upper()}.")
An example of inline evaluation.

Troubleshooting Potential Issues with f-strings

Despite their simplicity, f-strings have constraints and edge cases. Understanding these limitations prevents runtime syntax errors and unexpected behavior.

The following sections list specific technical issues and provide ways to correct them.

Backslashes in f-string

Python prohibits the use of backslashes directly inside the curly braces of an f-string. This restriction means one cannot use escape sequences like (\n) or (\t) within the expression part of the brace.

The following example will cause a SyntaxError:

print(f"Words: {'\n'.join(['apple', 'banana'])}")

To include a newline or tab inside a joined list, assign the escape sequence to a variable. Reference the variable inside the f-string to bypass the syntax limitation:

words = ['apple', 'banana']
newline = "\n"
print(f"Words:{newline}{newline.join(words)}")

Inline Comments in f-string

F-strings do not support the hash (#) symbol for comments within the replacement expressions. Including a comment inside the curly braces triggers a SyntaxError.

The following example code will fail:

print(f"Price: {100 # base price}")

Place comments on the line above the f-string or beside it outside the quotes:

price = 100 # base price
print(f"Price: {price}")

Printing Braces using f-string

Sometimes a string must include literal curly braces, such as when generating JSON or CSS code. Because f-strings use braces as delimiters, use the following escape sequence to display them:

{{ [evaluation] }}

For example:

val = 10
print(f"The value is {{ {val} }}")

Doubling the braces ({{) and (}}) tells Python to treat them as literal characters. The inner {val} still undergoes evaluation, while the outer double braces appear as single braces in the final output.

Printing Dictionaries Key-value Using f-string

Accessing dictionary keys requires attention to the type of quotes used. A conflict occurs if the quotes for the key match the quotes defining the f-string.

Use single quotes for the dictionary key if the f-string uses double quotes. This distinction allows the interpreter to identify where the key ends and where the string literal continues.

print(f"{person['name']}")

Conclusion

This article provided a comprehensive overview of f-strings in Python. It covered the syntax, provided examples, and offered steps to troubleshoot your code.

Next, learn How to Substring a String in Python.

Was this article helpful?
YesNo