String formatting is an essential tool in any Python developer's toolbox. F-strings (formatted string literals), introduced in Python 3.6, are a modern and powerful update to traditional string formatting methods. They are faster at runtime, more readable, and more concise. Once you start using them, you likely won't go back.
First, let's briefly look at the older methods f-strings improve upon.
The str.format()
method:
brother = "John"
sister = "Jane"
print("Hello, {0} and {1}".format(brother, sister))
String concatenation with +
:
folder = "/home/user/john/movies"
filename = "Big Buck Bunny.mp4"
print("The folder name is '" + folder + "' and the filename is '" + filename + "'.")
The modulo operator %
(C-style formatting):
print("The number %s is %d." % ("nineteen", 19))
All these methods work, but they can be verbose and hard to read, especially with multiple variables.
The Power and Simplicity of F-Strings
Now, let's see how f-strings can simplify the previous examples. You create an f-string by prefixing the string with the letter f
or F
.
Replacing str.format()
:
brother = "John"
sister = "Jane"
print(f"Hello, {brother} and {sister}")
Replacing concatenation:
folder = "/home/user/john/movies"
filename = "Big Buck Bunny.mp4"
print(f"The folder name is '{folder}' and the filename is '{filename}'.")
The output for both examples is identical to the originals, but the code is much cleaner.
Evaluating Expressions Inside F-Strings
You can even evaluate Python expressions directly inside the curly braces {}
.
Function calls:
import os
fullpath = "/home/user/john/movies/Big Buck Bunny.mp4"
print(f"The directory is: {os.path.dirname(fullpath)}")
Math expressions:
x = 10
y = 5
print(f"Ten plus five is {x + y}, not {x - y}.")
Displaying Literal Curly Braces
If you need to include literal curly braces in your output, you can escape them by doubling them up ({{
or }}
).
value = 42
print(f"The value is {{{value}}}")
Output:
The value is {42}
Debugging with F-Strings: Showing Variable Names and Values
F-strings have a powerful feature for debugging. By adding an equals sign =
after a variable, you can print both the variable's name and its value.
Instead of writing this:
this_is_a_long_variable_name = "some text"
print('this_is_a_long_variable_name =', this_is_a_long_variable_name)
You can simply write this:
this_is_a_long_variable_name = "some text"
print(f"{this_is_a_long_variable_name=}")
Output:
this_is_a_long_variable_name='some text'
Using Format Specifiers
All format specifiers from the str.format()
method are also compatible with f-strings. They follow the colon :
inside the curly braces. These specifiers are part of Python's Format Specification Mini-Language.
Formatting Numbers
You can easily format large numbers with separators for readability.
total = 1000000
print(f"Your new balance is: ${total:,}")
Output:
Your new balance is: $1,000,000
Controlling Decimal Precision
You can control the number of decimal places shown for floating-point numbers.
pi = 3.1415926535
print(f"Pi rounded to two decimal places is: {pi:.2f}")
Output:
Pi rounded to two decimal places is: 3.14
Padding and Alignment
You can align text within a certain space and choose a character for padding.
-
^
centers the text. -
<
left-aligns the text. -
>
right-aligns the text.
print(f"{'start':*^50}")
print(f"{'Next':=<50}")
print(f"{'Previous':_>50}")
print(f"{'End':^50}")
Output:
**********************start***********************
Next==============================================
__________________________________________Previous
End
String Representations: !s
and !r
F-strings allow you to specify which representation of an object to use: !s
for str()
(the default) and !r
for repr()
.
from datetime import datetime
now = datetime.now()
print(f"Using !s: {now!s}")
print(f"Using !r: {now!r}")
Output:
Using !s: 2025-07-13 18:29:00.123456
Using !r: datetime.datetime(2025, 7, 13, 18, 29, 0, 123456)
Comments in F-Strings (Python 3.12+)
Starting with Python 3.12, you can add comments inside an f-string expression. The comment must start with a #
and appear at the end of the expression.
value = 123.456
print(f"The value is {value:.2f # Round to 2 decimal places}")
Output:
The value is 123.46
Thank you for reading.
Buy my book on How not to become a broke software engineer on Gumroad or Amazon.
Top comments (0)