DEV Community

Cover image for F-Strings: The Ultimate Cheatsheet for Python String Formatting
Amoh Gyebi Ampofo
Amoh Gyebi Ampofo

Posted on

F-Strings: The Ultimate Cheatsheet for Python String Formatting

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))
Enter fullscreen mode Exit fullscreen mode

String concatenation with +:

folder = "/home/user/john/movies"
filename = "Big Buck Bunny.mp4"

print("The folder name is '" + folder + "' and the filename is '" + filename + "'.")
Enter fullscreen mode Exit fullscreen mode

The modulo operator % (C-style formatting):

print("The number %s is %d." % ("nineteen", 19))
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Replacing concatenation:

folder = "/home/user/john/movies"
filename = "Big Buck Bunny.mp4"

print(f"The folder name is '{folder}' and the filename is '{filename}'.")
Enter fullscreen mode Exit fullscreen mode

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)}")
Enter fullscreen mode Exit fullscreen mode

Math expressions:

x = 10
y = 5

print(f"Ten plus five is {x + y}, not {x - y}.")
Enter fullscreen mode Exit fullscreen mode

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}}}")
Enter fullscreen mode Exit fullscreen mode

Output:

The value is {42}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

You can simply write this:

this_is_a_long_variable_name = "some text"

print(f"{this_is_a_long_variable_name=}")
Enter fullscreen mode Exit fullscreen mode

Output:

this_is_a_long_variable_name='some text'
Enter fullscreen mode Exit fullscreen mode

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:,}")
Enter fullscreen mode Exit fullscreen mode

Output:

Your new balance is: $1,000,000
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output:

Pi rounded to two decimal places is: 3.14
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output:

**********************start***********************
Next==============================================
__________________________________________Previous
                       End
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output:

Using !s: 2025-07-13 18:29:00.123456
Using !r: datetime.datetime(2025, 7, 13, 18, 29, 0, 123456)
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output:

The value is 123.46
Enter fullscreen mode Exit fullscreen mode

Thank you for reading.

Buy my book on How not to become a broke software engineer on Gumroad or Amazon.

Top comments (0)