The release of Python 3.6 came with exciting functionalities. I want to speak about the feature called interpolated format string – f-strings for short- through this quick post. This new feature allows us to have a more readable, concise and even faster way of formatting string, in short words: pythonic code.
One of the most interesting features associated with the f-string is the capacity to include expressions which can be solved. The Python syntax is:
1 |
f "{variable or expression here}" |
As you can observe, it is simple compared to previous functions, and it is less prone to commit mistakes as can happen when you depend on the order of the variables such as string.format syntax. As I mentioned above, using F-strings also enables you to put a full Python expression within the
placeholder braces. See the following example:
1 2 3 4 5 6 7 8 9 10 |
# Evaluating expressions internally baseball_teams = [ ('Arizona Diamondbacks',1), ('Detroit Tigers', 4), ('Cincinnati Reds', 10), ] for i, (item, count) in enumerate(baseball_teams): f_string = f'Row {i+1}: {item.title():<20s} = {count}' print(f_string) |
It is interesting to remark on the capacity to include a format function inside of placeholder braces too. In this example, we formatted the length of the variable .. more explanation. By default, f-string use __str__(). Nonetheless, you could use __repr__()
which can be helpful in case you want to get the parable string representation of an object; you only need to include the conversion flag !r as in this example:
1 2 3 4 5 |
key = 'variable' value = 1.2345 f_string = f'{key !r:<10} = {value: .2f}' print(f_string) |
As in the previous example, you are able to apply a format to variables parsed, including the number of digits after the decimal, justification on the string, etc. You can find more details about it here.
Finally, the following example shows you the speed of both approaches. We are using a library called timeit, its usage is simple and consists in supplying a statement of the number of iterations to be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import timeit testcode_traditional = ''' name = "Octavio" age = 24 '%s is %s.' % (name, age) ''' testcode_fstring = ''' name = "Octavio" age = 24 f'{name} is {age}.' ''' print(timeit.timeit(stmt=testcode_traditional, number=10000)) print(timeit.timeit(stmt=testcode_fstring, number=10000)) |
Once you execute, please observe the time delta between both options and you will have an additional reason to start using f-string over any older approach. Last but not least, thanks to my colleague and large landowner Esteban (SRE rockstar) at Languagewire for sharing this syntax. Happy coding!