[python drops] f-strings


In this Python Drops episode we’re going to talk about f-strings, also known as Literal String Interpolation. This feature was added on Python 3.6 and the goal is making the String interpolation more readable. Interpolation is a fancy name to mount/create/construct a String from data you want to: a variable, a method return and so on.

Before it, the common way to interpolate Strings looked like this:

Format Strings (example from the oficial documentation)

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')

'Coordinates: 37.24N, -115.81W'

%-formatting (example from the oficial documentation)

>>> print('%(language)s has %(number)03d quote types.' %
...       {'language': "Python", "number": 2})

Python has 002 quote types.

And more… (this option I didn’t know TBH 😅):

Template Strings (example from the oficial documentation)

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')

'tim likes kung pao'

Reading this pieces of code, it’s possible to understand quickly what each one does, from Format String as the most readable to Template Strings as the less one. However, when we think about writting logs or emails or anything as a bigger String, the readability goes with the dogs. Having simple is better than complex in mind, the f-strings was born.

To use it, just add a f in the beginning of a String - it works with double or simple quotes.

>>> full_name = 'Maria Joaquina de Amaral Pereira Goes'
>>> print(f'Welcome, {full_name}')

Welcome, Maria Joaquina de Amaral Pereira Goes

The Strings are built during the execution time. You can do a lot of stuff with it, including adding expressions or call to other functions:

>>> print(f'Welcome, {nome_completo.split(" ")[0]}.')

Welcome, Maria.

>>> print(f'Local date/time: {datetime.now(): %B %d, %Y %H:%M:%S}')

Local date/time:  February 16, 2018 17:53:32

Also lambdas:

>>> f'{(lambda x: x*2)(3)}'

'6'

The docs are full of good examples. The Python source code is one of them. 👌🏽

Worth remembering that, despite being included recently, this feature doesn’t exclude or deprecate the others.


How about you? Are you using f-strings already? Any good tips to share? See ya!


Bonus! ✨

Elinaldo Monteiro have suggested the blog post The new f-strings in Python 3.6. The post author did a simple (and cool) benchmark with all the possible ways to interpolate Strings. It’s possible to check it out the execution time. The source code is here and the result below:

f-strings         2.996347602980677
format %          4.152905852010008
concat-strings    5.647188798990101
.format()         5.912839388009161
Template Strings  39.48270317300921

Impressive! But we couldn’t forget that the Template Strings has few validations to prevent code injection, a really handy feature used in cases where you receive the input from the user.

Translations


comments powered by Disqus