Python f-strings


Hey there! How are you doing? :)

Since past couple of days I’ve been attending the EuroPython conference at Bilbao, Spain and it has been an increíble experience so far! There are over a dozen amazing talks with something new to share every day and the super fun lightning talks at the end of the day. If for some reason you weren’t able to attend the conference then you may see the talks live at EuroPython YouTube channel.

In this blog I would like to talk briefly about PEP498 - Literal String Interpolation in Python. Python supports multiple ways to format text strings (%-formatting, format formatting and Templates). Each of these are useful in some ways but they do lack in other aspects. For eg. the simplest version of format style is too verbose.

place = “Bilbao, Spain”
“EuroPython is happening at {place}”.format(place=place)

Clearly, there is a redundancy. place is being used multiple times. Similarly, % formatting is limited with the types (int, str, double) that can be parsed.

f-strings are proposed in PEP498. f-strings are basically a literal strings with ‘f’ or ‘F’ as prefix. It embeds expressions using braces that are evaluated at runtime. Let’s see some simple examples:

place = “Bilbao, Spain”
print(f“EuroPython is happening at {place}”) # Simple enough, right?

def say_hello():
return “Hello”

print(f‘{say_hello()} there!’)

I think that’s simpler and better than other string formatting options. If this feature interests you and you want to learn more about it then I recommend checking out the PEP498 documentation.


Blog comments powered by Disqus