Python F Strings

Python F Strings
Python F Strings

As of Python 3.6 per PEP 498 a new way of string formatting was introduced called F strings. While Python already had multiple multiple ways of string formatting, f strings aimed to provide a way to add embedded expressions directly within a string while using minimal formatting to give the best readability. In this post I will give a few examples of using f-strings in Python.

 

Validate Environment

The first thing you need to do is validate that you are running Python 3.6 or higher on your machine, to do this issue the following command.

If you do not have at least Python 3.6 you will need to install it.

 

Syntax

The only thing you need to do to create an f-string is prepend an “f” before the opening quotes of the string like below.

This is an example of storing an f-string in a variable. While this f-string has no practical use as it does not embed any expressions it serves to just show the syntax

 

Embed Variables

Using f-strings you are able to directly embed variales within the string without any additional code syntax other than the opening and closing curly braces. See the code below for an example.

When we run that code we get the following output.

 

Embed Function Output

You are also able to embed the output from functions directly within the string. See the example below.

When running that code we get the following output

 

In Conclusion

F-strings are not all that different from the current ways of string formatting but with the ability of embedding expressions directly within the string itself in my opinion helps increase the readability of code bases that use it. Unfortunately you cant use f-strings in legacy code bases but if your project does need to run using a Python interpreter previous to 3.6 I highly suggest using f-strings. If this article was helpful please share, and if you are looking for other Python articles please check out my Python article collection.

 

Be the first to comment

Leave a Reply

Your email address will not be published.


*