Python 3.6 F-strings

Posted

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 format
nameVar = Andrew
print("Hello, {}!".format(nameVar))

Hello, Andrew!

nameVar = Andrew
print("Hello, {name}!".format(name=nameVar))

Hello, Andrew!

Using %-formatting
nameVar = Andrew
print("Hello, %s!" % nameVar)

Hello, Andrew!

Using f-strings
nameVar = 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)

More posts

Balloon Shooting Challenge

Writing a game with Microsoft's Small Basic language!

Posted

Unifi and Java

Trusting in the ability of programmers to implement working auto updaters

Posted