This tutorial covers the concept of Python f-strings and explains string formatting in detail with self-explanatory examples. It is an implementation of the PEP 498 specifications for formatting Python strings in an entirely new way. It is available in Python version 3.6 and above.
Python f-string uses a new convention that requires every string should begin with the ‘f’ prefix. And hence, it derives its name from this synthesis. One of the main advantages that it brings is making the string interpolation easier. Also, it insists on having a simple way to use Python expressions within a string literal for formatting.
How to Use F-Strings for String Formatting
Once you get used to using f-strings, you will find it the easiest and the best way to handle strings. Let’s unwrap every little detail about f-string step by step and with examples.
By the way, there are several methods of formatting a string in Python. Some of them are by using the % operator and the format() function. If interested, please read about them as well.
What are F-strings in Python?
F-strings are a new method for handling strings in Python. It is based on the PEP 498 design specs. To create an f-string, you need to prefix it with the ‘f’ literal. Its primary purpose is to simplify the string substitution.
It pushes for a minimal syntax and evaluates expressions at run-time. This feature is not available in any version below Python 3.6. Hence, use it or a higher version of Python.
Syntax
You can use the below statement to create an f-string in Python.
f'Python {expr}'
The expr can be anything from a constant, an expression, a string or number, a Python object, etc.
Basic Example
Here’s a simple example to illustrate its usage.
version = 3.6 feature = 'f-string' str_final = f'Python {feature} was introduced in version {version}.' print(str_final)
After executing the code, you get to see this result:
Python f-string was introduced in version 3.6.
Simple Ways to Use F-strings
In this section, we’ve brought up several elementary cases of f-strings. Check below:
title = 'Joshua' experience = 24 dyn_str = f'My title is {title} and my exp is {experience}' print(dyn_str) # We can use f or F interchangeably print(F'My title is {title} and my exp is {experience}') title = 'Sophia' experience = 14 # dyn_str doesn't get re-evaluated, if the expr changes later. print(dyn_str)
Python is an interpreted language and runs instructions one by one. If the f-string expression is evaluated, then it won’t change whether the expression changes or not. Hence, in the above example, the dyn_str value is intact even after the title and experience variables have different values.
Using F-strings in Conversions
The f-strings allow conversion like converting a Python date-time to other formats. Here are some examples:
from datetime import datetime # Initializing variables title = 'Abraham' experience = 22 cur_date = datetime.now() # Some simple tests print(f'Exp after 10 years will be {experience + 10}.') # experience = 32 print(f'Title in quotes = {title!r}') # title = 'Abraham' print(f'Current Formatted Date = {cur_date}') print(f'User Formatted Date = {cur_date:%m-%d-%Y}')
After code execution, the outcome is:
Exp after 10 years will be 32. Title in quotes = 'Abraham' Current Formatted Date = 2019-07-14 07:06:43.465642 User Formatted Date = 07-14-2019
Generate Raw String from F-string
F-strings can also produce raw string values.
To print or form a raw string, we need to prefix it using the ‘fr’ literal.
from datetime import datetime print(f'Date as F-string:\n{datetime.now()}') print(fr'Date as raw string:\n{datetime.now()}')
It tells us the difference between f vs. r strings. The output is:
Date as F-string: 2019-07-14 07:15:33.849455 Date as raw string:\n2019-07-14 07:15:33.849483
Using F-string with Classes
Apart from using f-string to format Python strings, we can use them to format class objects and their attributes.
Here is a sample Python class using f-string for formatting its members:
class Student: age = 0 className = '' def __init__(self, age, name): self.age = age self.className = name def __str__(self): return f'[age={self.age}, class name={self.className}]' std = Student(8, 'Third') print(std) print(f'Student: {std}\nHis/her age is {std.age} yrs and the class name is {std.className}.')
After running the above code, you get to see this outcome:
[age=8, class name=Third] Student: [age=8, class name=Third] His/her age is 8 yrs and the class name is Third.
Using F-string in a Function
Let’s create one of our custom functions and see how can it be called from the f-string
def divide(m, n): return m // n m = 25 n = 5 print(f'Divide {m} by {n} = {divide(m, n)}')
The above snippet outputs the following:
Divide 25 by 5 = 5
Use Whitespaces in F-strings
Python dismisses any whitespace character that appears before or after the expression in an f-string. However, if there is some in the overall sentence, then it is eligible to be displayed.
kgs = 10 grams = 10 * 1000 print(f'{ kgs } kg(s) equals to { grams } grams.')
When you run the sample, you get to see this output:
10 kg(s) equals to 10000 grams.
F-string with Python Lambda
Anonymous function, also known as Python lambda expression, can work alongside f-strings. However, you need to be cautious when using “!” or “:” or “}” symbols. If they aren’t inside parentheses, then it represents the end of an expression.
Also, lambda expr uses a colon which can cause adverse behavior. See below.
lambda_test = f"{lambda x: x * 25 (5)}"
The above statement would cause the following error:
File "", line 1 (lambda x) ^ SyntaxError: unexpected EOF while parsing
To use a colon safely with Lambda, wrap it inside parentheses. Let’s check out how:
lambda_test = f"{(lambda x: x * 25) (5)}" print(lambda_test)
After running the updated code, you see the following:
125
If you are interested, then also read different usages of Lambda in Python.
Braces within an F-string
If you like to see a pair of “{}” in your string, then have double braces to enclose:
lambda_test = f"{{999}}" print(lambda_test)
Output:
{999}
If you try with triple braces, then also, it will only show one set of braces.
lambda_test = f"{{{999}}}" print(lambda_test)
Output:
{999}
Backslashes within F-string
We use backslash escapes in a part of a Python f-string. But, we can’t use them to escape inside the expression.
lambda_test = f"{"Machine Learning"}" print(lambda_test)
The above code produces the following error:
File "jdoodle.py", line 2 lambda_test = f"{"Machine Learning"}" ^ SyntaxError: invalid syntax
We can fix this by placing the result of the expression and using it directly in the f-string:
topic = "Machine Learning" lambda_test = f"{topic}" print(lambda_test)
The result is:
Machine Learning
Also, note that you should not insert comments (using a “#” character ) inside f-string expressions. It is because Python would treat this as a syntax error.
Before You Leave
We hope that after wrapping up this tutorial, you should feel comfortable using the Python f-string. However, you may practice more with examples to gain confidence.
Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.