PEP 498 introduced a new string formatting mechanism called Literal String Interpolation.
We’ll call them F-strings, because of the leading f
character that appears before the string literals.
The PEP really says it all but sure we’ll go through it again, why not!
Format:f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
Using string formatnameVar = Andrew
print("Hello, {}!".format(nameVar))
Hello, Andrew!
nameVar = Andrew
print("Hello, {name}!".format(name=nameVar))
Hello, Andrew!
Using %-formattingnameVar = Andrew
print("Hello, %s!" % nameVar)
Hello, Andrew!
Using f-stringsnameVar = Andrew
print(f"Hello, {nameVar}!")
Hello, Andrew!
Escaping f-strings
What if we wanted to print out “{var}”print(f"{{var}}")
{var}
What if we wanted to print out “{{var}}”print(f"{{{{var}}}}")
{{var}}
In terms of speed, they’re much faster than %-formatting
and the str.format()
function! (source: Hacker Noon)