Both ternaries ("if expressions") and comprehensions ("for expressions") are allowed inside f-strings. However, they must be part of expressions that evaluate to strings. For example, key: value is a dict pair, and f"{key}: {value}" is required to produce a string.

>>> dct = {'a': 1, 'b': 2}
>>> newline = "\n"  # \escapes are not allowed inside f-strings
>>> print(f'{newline.join(f"{key}: {value}" for key, value in dct.items())}')
a: 1
b: 2

Note that if the entire f-string is a single format expression, it is simpler to just evaluate the expression directly.

>>> print("\n".join(f"{key}: {value}" for key, value in dct.items())))
a: 1
b: 2

Expressions inside format strings still follow their regular semantics. For example, a ternary may test whether an existing name is true. It will fail if the name is not defined.

>>> c, name = "Hello", ""
>>> f'{c} {name if name else "unknown"}'
'Hello unknown'
>>> del name
>>> f'{c} {name if name else "unknown"}'
NameError: name 'name' is not defined
Answer from MisterMiyagi on Stack Overflow
🌐
Real Python
realpython.com › python-f-strings
Python's F-String for String Interpolation and Formatting – Real Python
November 30, 2024 - The timeit.timeit() function inside the for loop runs each interpolation tool a million times and returns the total execution time. Then, the function prints the result to the screen. Note how your f-string in the call to print() takes advantage of format specifiers to conveniently format the code’s output.
🌐
Python for Network Engineers
pyneng.readthedocs.io › en › latest › book › 08_python_basic_examples › f-string.html
Formatting lines with f-strings - Python for network engineers
When using f-strings in loops an f-string must be written in body of the loop to «catch» new variable values within each iteration:
🌐
Reddit
reddit.com › r/learnpython › using f-string's with a list
r/learnpython on Reddit: using f-string's with a list
May 3, 2023 -

just thought id make a post incase anyone has an issue using f-string with a list. i moved on from using .format() to using f-string. i have found it pretty easy to get adjusted to but i was struggling with using specific values within a list, i treid a few methods like:

names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {0} {1} {2}'(*names)
print(text)

names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {*0} {*1} {*2}'(names)
print(text)

names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {[0]} {[1]} {[2]}'(names)
print(text)

all came back with errors and left me stuck on how to use f-string with a list until i watched Corey Schafers video, within the half an hour i was pretty much trying to brute force it, reaching the same error, i found out the correct way of interlopoing a list with a f-string is:

names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {names[0]}, {names[1]}, {names[2]}'
print(text)

just thought id make the post incase anyone else is unsure on how.

🌐
W3Schools
w3schools.com › python › python_string_formatting.asp
Python String Formatting
To format values in an f-string, add placeholders {}, a placeholder can contain variables, operations, functions, and modifiers to format the value. ... A placeholder can also include a modifier to format the value.
🌐
Reddit
reddit.com › r/learnpython › why do people use .format() method when f string literal exists?
r/learnpython on Reddit: Why do people use .format() method when f string literal exists?
March 20, 2020 -

Hello all,

I seem to encounter a lot of documentation and tutorials that use .format() method instead of f string literals.

Personally,

print("I can't seem to {} of a {} why someone {} {} {}".format('think', 'reason', 'would', 'prefer', 'this'))

versus

easily = "easily"
sentence = "sentence"
this = "this"
print(f"A much more {easily} readable {sentence} such as {this}")

F string literal is always much easier to decipher and thus avoid errors.

Perhaps there's some benefit of .format() that I'm unaware of. Googling hasn't brought up much on the debate.

Cheers!

🌐
Reddit
reddit.com › r/learnpython › what's better to use? (%), (f"string") or (.format())?
r/learnpython on Reddit: What's better to use? (%), (f"string") or (.format())?
July 25, 2024 -

I was trying to make a, silly program in which you can do some random things. I used arguments (%)in the past, but it's a bit hard to write like the identification of the variable, like there is so much types (%s, %f, %2f, %d, %g, %e...) and I want to take the easiest to write or the easiest to debug.

here are some examples of using each one:

  using (%):
name = "Imaginary_Morning"
age = 13
print("This profile is called %s and it has %d years old." % (name, age))
  
using (f"string"):
name = "Imaginary_Morning"
age = 13
print(f"This profile is called {name} and it has {age} years old.")

  using (.format()):
name = "Imaginary_Morning"
age = 13
print("This profile is called {} and it has {} years old.".format(name, age))
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › python-f-string
Python f-string: A Complete Guide | DataCamp
December 3, 2024 - When dealing with loops, proper f-string usage becomes particularly important. Here's a comparison of different approaches: # Loop performance comparison data = [("Alice", 95), ("Bob", 87), ("Charlie", 92)] # Less efficient approach - creating new format string each time def format_inefficient(): result = [] for name, score in data: result.append("Name: {} | Score: {}".format(name, score)) return "\n".join(result) # More efficient approach - create template once def format_efficient(): template = "Name: {} | Score: {}" result = [] for name, score in data: result.append(template.format(name, sc
🌐
GeeksforGeeks
geeksforgeeks.org › python › formatted-string-literals-f-strings-python
f-strings in Python - GeeksforGeeks
September 25, 2025 - Note: F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format(). In f-strings, you can use single (') or double (") quotes.
🌐
Python
peps.python.org › pep-0498
PEP 498 – Literal String Interpolation | peps.python.org
The resulting value is used when building the value of the f-string. Note that __format__() is not called directly on each value. The actual code uses the equivalent of type(value).__format__(value, format_spec), or format(value, format_spec). See the documentation of the builtin format() function for more details.
🌐
ZetCode
zetcode.com › python › fstring
Python f-string - formatting strings in Python with f-string
Any valid Python expression can be placed within the curly braces, allowing you to perform calculations or manipulate data inline as you format your output. ... #!/usr/bin/python bags = 3 apples_in_bag = 12 print(f'There are total of {bags * apples_in_bag} apples') Here, the expression bags * apples_in_bag is evaluated inside the f-string, and its result is inserted into the output. This makes f-strings very flexible for dynamic string construction.
🌐
Real Python
realpython.com › how-to-python-f-string-format-float
How to Format Floats Within F-Strings in Python – Real Python
April 24, 2024 - You achieve this by nesting the precision replacement field {length} within the format specifier. The asterisk (*) defines the padding character to be used, while the caret (^) symbol ensures the output is centered. The padded_words list is created using a list comprehension. The .split() method is called on the content of the text variable, which separates out the original string by its space characters and produces a list containing its three words. The for loop then iterates over each of these and passes them to .format().
🌐
Medium
pravash-techie.medium.com › python-going-beyond-basic-string-formatting-using-f-string-cba87ddb78fb
Python: Going Beyond Basic String Formatting using f-string | by Pravash | Medium | Medium
March 23, 2023 - An f-string is a string literal that is prefixed with the letter “f”. It allows developers to embed expressions inside string literals, using curly braces {}. These expressions are evaluated at runtime and the resulting values are inserted ...
🌐
W3Schools
w3schools.com › python › python_strings_format.asp
Python - Format Strings
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... age = 36 #This will produce an error: txt = "My name is John, I am " + age print(txt) Try it Yourself » · But we can combine strings and numbers by using f-strings or the format() method!
🌐
Bentley
cissandbox.bentley.edu › sandbox › wp-content › uploads › 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
Updated 2022 A Guide to Formatting with f-strings in Python
When variable = math.pi, the f-string · understands that variable is a floating-point number and displays it as such. You can also · use specify the type as f and use spacing in the output. The following are examples of the exponent notation and the percentage notation: ... There are several options when formatting floating point numbers. The number of decimal · places, the use of the number separator character, and forcing a plus (+) or minus (-) sign can
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.3 documentation
For example: >>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142. More information can be found in the printf-style String Formatting section. open() returns a file object, and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)
🌐
Built In
builtin.com › data-science › python-f-string
Guide to String Formatting in Python Using F-strings | Built In
In this guide, we’ll see how to format strings in Python using f-string. We’ll also learn how to add variables, comma separators, right/left padding with zeros, dates and more. To follow this tutorial, make sure you have Python 3.6 or above. Otherwise, f-strings won’t work. F-string provides a better syntax for adding variables to strings.
Top answer
1 of 6
107

I'm afraid that it will be deprecated during the next Python versions

Don't be, str.format does not appear (nor has a reason) to be leaving any time soon, the PEP that introduced fprefixed-strings even states in its Abstract:

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

Formatted strings were introduced to address some of the shortcomings other methods for formatting strings had; not to throw the old methods away and force god-knows how many projects to use f-string's if they want their code to work for Python 3.6+.


As for the performance of these, it seems my initial suspicion that they might be slower is wrong, f-strings seem to easily outperform their .format counterparts:

➜ cpython git:(master) ./python -m timeit -s "a = 'test'" "f'formatting a string {a}'"
500000 loops, best of 5: 628 nsec per loop
➜ cpython git:(master) ./python -m timeit "'formatting a string {a}'.format(a='test')"
100000 loops, best of 5: 2.03 usec per loop

These were done against the master branch of the CPython repository as of this writing; they are definitely subject to change:

  • f-strings, as a new feature, might have possible optimizations
  • Optimizations to CPython might make .format faster (e.g Speedup method calls 1.2x)

But really, don't worry about speed so much, worry about what is more readable to you and to others.

In many cases, that's going to be f-strings, but there's some cases where format is better.

2 of 6
42

To build on Jim's answer and address your performance concern, I used python's dis module to compare the bytecode instructions for two syntactically different, but functionally equivalent functions.

import dis

def f1():
    a = "test"
    return f"{a}"

def f2():
    return "{a}".format(a='test')

print(dis.dis(f1))
print(dis.dis(f2))

The result of which is:

 11           0 LOAD_CONST               1 ('test')
              2 STORE_FAST               0 (a)

 12           4 LOAD_FAST                0 (a)
              6 FORMAT_VALUE             0
              8 RETURN_VALUE
None
 15           0 LOAD_CONST               1 ('{a}')
              2 LOAD_ATTR                0 (format)
              4 LOAD_CONST               2 ('test')
              6 LOAD_CONST               3 (('a',))
              8 CALL_FUNCTION_KW         1
             10 RETURN_VALUE
None

One can see that the f-string handles the formatting without attribute or function calls, which can impose type checking and memory overhead. According to timeit this results in a roughly 3x performance gain (for my specific functions)

>>> timeit.timeit('f1()', 'from __main__ import f1', number=100000)
0.012325852433775708
>>> timeit.timeit('f2()', 'from __main__ import f2', number=100000)
0.036395029920726074
🌐
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.3 documentation
In addition, the Formatter defines a number of methods that are intended to be replaced by subclasses: ... Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion).