In this lesson, you’ll learn how you can accomplish simpler debugging with f-strings. f-strings were introduced in Python 3.6, and have become very popular. They might be the most common reason for Python libraries only being supported on version 3.6 and later. An f-string is a formatted string literal. You can recognize it by the leading f
:
>>> style = "formatted"
>>> f"This is a {style} string"
'This is a formatted string'
When you use f-strings, you can enclose variables and even expressions inside curly braces. They will then be evaluated at runtime and included in the string. You can have several expressions in one f-string:
>>> import math
>>> r = 3.6
>>> f"A circle with radius {r} has area {math.pi * r * r:.2f}"
'A circle with radius 3.6 has area 40.72'
In the last expression, {math.pi * r * r:.2f}
, you also use a format specifier. Format specifiers are separated from the expressions with a colon.
.2f
means that the area is formatted as a floating point number with 2 decimals. The format specifiers are the same as for .format()
. See the official documentation for a full list of allowed format specifiers.
In Python 3.8, you can use assignment expressions inside f-strings. Just make sure to surround the assignment expression with parentheses:
>>> import math
>>> r = 3.8
>>> f"Diameter {(diam := 2 * r)} gives circumference {math.pi * diam:.2f}"
'Diameter 7.6 gives circumference 23.88'
However, the real f-news in Python 3.8 is the new debugging specifier. You can now add =
at the end of an expression, and it will print both the expression and its value:
>>> python = 3.8
>>> f"{python=}"
'python=3.8'
This is a short-hand that will typically be most useful when you’re working interactively or adding print statements to debug your script. In earlier versions of Python, you needed to spell out the variable or expression twice to get the same information:
>>> python = 3.7
>>> f"python={python}"
'python=3.7'
You can add spaces around =
, and use format specifiers as usual:
>>> name = "Eric"
>>> f"{name = }"
"name = 'Eric'"
>>> f"{name = :>10}"
'name = Eric'
The >10
format specifier says that name should be right-aligned within a 10 character string. =
works for more complex expressions as well:
>>> f"{name.upper()[::-1] = }"
"name.upper()[::-1] = 'CIRE'"
For more information about f-strings, see Python 3’s f-Strings: An Improved String Formatting Syntax (Guide) and the associated video course.
Prabhath Kota on May 3, 2020
Thanks for the article. Good to know debugging with fstrings in 3.8 & optimizations