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.
Prabhath Kota on May 3, 2020
Thanks for the article. Good to know debugging with fstrings in 3.8 & optimizations