This article will cover a guide on using the new “F” type string formatting syntax added to recent versions of Python. Simply termed as “f-strings” or “formatted string literals”, these expressions allow you to use Python variables, functions and statements directly in the text of a string. They also help in keeping the code clean, as you can use inline expressions without resorting to any kind of ordered substitutions that are usually part of the other string formatting techniques available in Python. F-strings are included by default in Python 3.6 and newer builds.
Basic Syntax and Usage
To use the f-string format, you need to prefix any string with “f” or “F” character, just before the starting quote symbol. Here is an example:
text2 = F"This is another string."
print (text1)
print (text2)
As you can see, both strings are prefixed by either “f” or “F” characters. You can also use f-strings before triple quotes. Triple quotes can be used to represent strings “as is” and you don’t need to escape characters in a string wrapped in triple quotes. After running this code sample, you should get the following output:
This is another string.
The example above just shows simple usage of f-strings where they are exactly the same as standard string type objects. The power of f-strings comes from inline expressions that you can wrap in curly braces. Here is an example showing inline variables being used in the f-strings:
second = "2nd"
text1 = f"This is the {first} string."
text2 = F"This is the {second} string."
print (text1)
print (text2)
As you can see in the example, curly braces have been used twice in f-strings. Expressions and variables inside curly braces within f-strings are evaluated by Python and then they are substituted with the results returned by the original expressions. After running the above code sample, you should get the following output:
This is the 2nd string.
If you are using a text editor with proper syntax highlighting for Python, you will notice that the curly braces are represented in a different color code, indicating their difference with other characters in the same string.
You can use curly braces any number of times in f-strings, as shown in the example below:
second = "2nd"
text = f"This is the {first} string. This is the {second} string."
print (text)
After running the above code sample, you should get the following output:
You may have used other string formatting and substitution methods in Python, mainly the “format” method and “%s” special symbol. The format method requires you to specify a numerical index for variables that will be evaluated within the string. The “%s” formatting syntax requires you to supply positional arguments in order of appearance. Here is a comparison of all three types of formatting patterns:
second = "2nd"
text = "This is the {0} string. This is the {1} string.".format(first, second)
print (text)
text = "This is the %s string. This is the %s string." % (first, second)
print (text)
text = f"This is the {first} string. This is the {second} string."
print (text)
As you can see in the code sample, f-strings provide a much more readable and cleaner syntax by using inline variables. You can use variables and expressions exactly at the place where you want the substitution to occur. No need to supply positional arguments or indexes.
After running the above code sample, you should get the following output:
This is the 1st string. This is the 2nd string.
This is the 1st string. This is the 2nd string.
Using Advanced Expressions in F-strings
You can use mathematical operators, call functions, round numbers and basically use any arbitrary one liner Python expression within the curly braces in f-strings.
You can use the “:” (colon) symbol to control the width of the evaluated value. If the evaluated value is of “int” or “float” type, it will be rounded. Below is a code sample:
points = 90.235689
text = f"""This is a rounded number: {points:.3f} | This is a ten character wide string: "{name:10}"."""
print (text)
The “.3f” modifier rounds the number upto 3 digits. You can extend the width of a string and fill it with whitespaces by supplying a number after the colon symbol. After running the above code sample, you should get the following output:
You can know more about all such modifiers and symbols by visiting official Python documentation available here.
You can also use advanced one liner statements within f-strings. The example below shows usage of list comprehension inside an f-string:
print (text)
In the curly braces, you can see list comprehension being used to generate a list from a range of 10 numbers. After running the above code sample, you should get the following output:
You can call any function in curly braces within the f-strings. You can also supply necessary arguments when calling them. Here is a code sample:
text = f"""The length of list is: {len(numberlist)}"""
print (text)
The code sample illustrates invoking the “len” method in curly braces. This is a built-in Python method, but you can call your own custom functions as well. After running the above code sample, you should get the following output:
Conclusion
F-strings provide a better string formatting methodology overcoming limitations of other string formatting systems available in Python. They are easy to read and use. They do not depend on positional arguments and keep the code clean, making it easy to debug expressions and statements.