F strings are just a nice way to insert variables into a template string. Yes, there are other ways - but f strings are usually the best. What way would you use instead? Answer from fiddle_n on reddit.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_string_formatting.asp
Python String Formatting
Before Python 3.6 we had to use the format() method. F-string allows you to format selected parts of a string.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and Output โ€” Python 3.14.6 documentation
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)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ formatted-string-literals-f-strings-python
f-strings in Python - GeeksforGeeks
May 16, 2026 - An f-string is created by adding f before the string and placing variables or expressions inside {}. ... Example 1: This example formats and prints the current date using an f-string.
๐ŸŒ
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
Percentage. Multiplies the number by 100 and displays in fixed ('f') format, ... The variable, variable, is enclosed in curly braces { }. When variable = 10, the f-string
๐ŸŒ
Real Python
realpython.com โ€บ python-f-strings
Python's F-String for String Interpolation and Formatting โ€“ Real Python
November 30, 2024 - Python f-strings offer a concise and efficient way to interpolate variables, objects, and expressions directly into strings. By prefixing a string with f or F, you can embed expressions within curly braces ({}), which are evaluated at runtime.
๐ŸŒ
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())?
November 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
๐ŸŒ
OpenStax
openstax.org โ€บ books โ€บ introduction-python-programming โ€บ pages โ€บ 3-2-formatted-strings
3.2 Formatted strings - Introduction to Python Programming | OpenStax
March 13, 2024 - A formatted string literal (or f-string) is a string literal that is prefixed with "f" or "F". A replacement field is an expression in curly braces ({}) inside an f-string. Ex: The string f"Good morning, {first} {last}!" has two replacement ...
๐ŸŒ
DEV Community
dev.to โ€บ tusharsadhwani โ€บ what-the-f-strings-391c
What the f-strings? - DEV Community
July 11, 2021 - The original formatting using the % sign has existed in Python ever since version 1.x (and even before that in C, which is where this feature's inspiration comes from). It allowed you to do most string formatting very easily, even though the syntax was a bit unusual: it uses % flags in your string, which get replaced by the values you pass in.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ formatted-strings
Python Formatted Strings / f-string formatting Guide
Start your coding journey with Python. Learn basics, data types, control flow, and more ... name = "Alice" item_count = 5 price = 19.99 # Basic f-string usage greeting = f"Hello, {name}." print(greeting) # Outputs: Hello, Alice. # Using expressions and number formatting total_cost = item_count * price receipt = f"Your total is ${total_cost:.2f} for {item_count} items." print(receipt) # Outputs: Your total is $99.95 for 5 items.
๐ŸŒ
Fstring
fstring.help โ€บ cheat
Python f-string cheat sheet
Type f with precision .n displays n digits after the decimal point. Type g with precision .n displays n significant digits in scientific notation. Trailing zeros are not displayed. ... An empty type is synonymous with d for integers. These format specifications only work on integers (int). ... These format specifications work on strings ...
๐ŸŒ
DEV Community
dev.to โ€บ erictleung โ€บ print-fixed-fields-using-f-strings-in-python-26ng
Print fixed fields using f-strings in Python - DEV Community
August 20, 2020 - Formatting strings in Python is very common. Older styles use a combination of % and .format() to format strings. Newer styles use what are called f-strings.
Top answer
1 of 16
995

To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

"Hello %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

"Hello %s" % (name,)   # supply the single argument as a single-item tuple

which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

Only use it for backwards compatibility with Python 2.5.


To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression log.debug("some debug info: %s" % some_info) will first evaluate the string to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

2 of 16
320

Something that the modulo operator ( % ) can't do, afaik:

tu = (12,45,22222,103,6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)

result

12 22222 45 22222 103 22222 6 22222

Very useful.

Another point: format(), being a function, can be used as an argument in other functions:

li = [12,45,78,784,2,69,1254,4785,984]
print map('the number is {}'.format,li)   

print

from datetime import datetime,timedelta

once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8,  minutes=20)

gen =(once_upon_a_time +x*delta for x in xrange(20))

print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))

Results in:

['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']

2010-07-01 12:00:00
2010-07-14 20:20:00
2010-07-28 04:40:00
2010-08-10 13:00:00
2010-08-23 21:20:00
2010-09-06 05:40:00
2010-09-19 14:00:00
2010-10-02 22:20:00
2010-10-16 06:40:00
2010-10-29 15:00:00
2010-11-11 23:20:00
2010-11-25 07:40:00
2010-12-08 16:00:00
2010-12-22 00:20:00
2011-01-04 08:40:00
2011-01-17 17:00:00
2011-01-31 01:20:00
2011-02-13 09:40:00
2011-02-26 18:00:00
2011-03-12 02:20:00
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
Top answer
1 of 2
3
Here's what I have as a reference. Basically a summary of the Format Specification Mini-Language . This would all go after a : in the f-string curly braces. So if you want a float with 2 decimal place precision, with * as fill and right aligned in a field width of 10 characters you'd do f"{val:*>10.2f}" [[fill]align][sign][#][0][minimumwidth][.precision][type] Fill: Add a character to fill with. Must be followed by Align flag. Align: '<' - Forces the field to be left-aligned within the available space (This is the default.) '>' - Forces the field to be right-aligned within the available space. '=' - Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form '+000000120'. This alignment option is only valid for numeric types. '^' - Forces the field to be centered within the available space. Sign: '+' - indicates that a sign should be used for both positive as well as negative numbers '-' - indicates that a sign should be used only for negative numbers (this is the default behavior) ' ' - indicates that a leading space should be used on positive numbers #: Flags alternate numbering formats; binary, octal, and hexadecimal output will be prefixed with '0b', '0o', and '0x', respectively. 0: Zero-padding. Equivalent to fill '=' and character of '0' Minimumwidth: Min width of the field. Precision: Decimal places for floats or max field size for non-numeric types. Type: Integers: 'b' - Binary. Outputs the number in base 2. 'c' - Character. Converts the integer to the corresponding Unicode character before printing. 'd' - Decimal Integer. Outputs the number in base 10. 'o' - Octal format. Outputs the number in base 8. 'x' - Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' - Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' - Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. '' (None) - the same as 'd' Floats: 'e' - Exponent notation. Prints the number in scientific notation using the letter 'e' to indicate the exponent. 'E' - Exponent notation. Same as 'e' except it converts the number to uppercase. 'f' - Fixed point. Displays the number as a fixed-point number. 'F' - Fixed point. Same as 'f' except it converts the number to uppercase. 'g' - General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to 'e' exponent notation. 'G' - General format. Same as 'g' except switches to 'E' if the number gets to large. 'n' - Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters. '%' - Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign. '' (None) - similar to 'g', except that it prints at least one digit after the decimal point.
2 of 2
1
A cheat sheet for f-string would be too short and kind of useless since f-string are super simple. If you want to put a number just do it. Ex. name: str = "Albus Dumbledore" age: int = 116 print(f"Name: {name}, Age: {age}") As you can see, I simply put age (which is an int) inside 2 brackets in the string (don't forget the f) and let Python do it's magic. (If you want you can use the example above as your cheat sheet)
๐ŸŒ
Medium
medium.com โ€บ @johnidouglasmarangon โ€บ padding-f-strings-in-python-977b17edbd36
Padding f-strings in Python
February 18, 2022 - number = 2022 padding = ... octal 3746 >>> hex 7E6 >>> binary 11111100110 ... This is a way to use a set of format strings that will be interpreted together....
๐ŸŒ
DEV Community
dev.to โ€บ seracoder โ€บ python-string-formatting-a-comprehensive-guide-to-f-strings-869
Python String Formatting: A Comprehensive Guide to F-strings - DEV Community
February 13, 2024 - F-strings, introduced in Python 3.6 and later versions, provide a concise and readable way to embed expressions inside string literals. They are created by prefixing a string with the letter โ€˜fโ€™ or โ€˜Fโ€™. Unlike traditional formatting ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_strings_format.asp
Python - Format Strings
To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations. ... A placeholder can contain variables, operations, functions, and modifiers to ...
๐ŸŒ
Real Python
realpython.com โ€บ python-formatted-output
A Guide to Modern Python String Formatting Tools โ€“ Real Python
February 1, 2025 - You create an f-string in Python by prepending a string literal with an f or F and using curly braces to include variables or expressions. You can use variables in Pythonโ€™s .format() method by placing them inside curly braces and passing them ...