Python f strings, or formatted string literals, is a syntax for handling string formatting.
Python 3.6 introduced f strings as a way to make string formatting more readable, concise, and less error-prone compared with previous ways of doing string formatting. This tutorial will walk you through how to make use of Python f strings to format strings.
What are python f strings?
We express an f-string by using the prefix character f in front of an ordinary string literal. We can then surround any expression inside the f-string with curly braces. For example
f"The sum 4 + 5 is {4 + 5}"
when evaluated, gives
"The sum 4 + 5 is 9"
Multi-lines in python f strings
A multi-line f-string allows us to express an f-string over more than one line. The next example shows the multiline f-string python code
message = (
f"The sum of 9 and 5 is {9 + 5}"
f" and their difference is {9 – 5}"
)
print(f"{message}")
the output for the program is
The sum of 9 and 5 is 14 and their difference is 4
The lines containing the curly braces need an f-prefix, or else python will not evaluate the expressions in the curly braces.
Using variables and expressions in python f strings
Variables can be expressed in an f-string by enclosing the variable in curly braces {}
. For example,
name = "Viktor"
age = 37
print(f"{name} is {age} years old")
the program will have the following output
Victor is 37 years old
We can see from the output that the variables were replaced with their values.
Also, we can assign f-strings to variables as regular strings. After assignment, the variable will contain a string with the necessary replacements and evaluations made. The next example builds a person’s full name from the person’s first name and last name, and then prints out the full name
first_name = "Janet"
last_name = "Doe"
full_name = f"{first_name} {last_name}"
surname_first = f"{last_name}, {first_name}"
print(full_name)
print(surname_first)
the output will resemble the following
Janet Doe
Doe, Janet
We can also put expressions within the curly braces. For example
length = 8
width = 4
print(f"The perimeter of the rectangle is {2*(length + width)}cm, and the area is {length * width}sq.cm")
The output will be
The area of the rectangle is 24cm, and the area is 32sq.cm
Using Conditional Expressions in python f strings
With conditional expressions, we can make decisions concerning what value to return in an f-string. Conditional expressions take three arguments in the following order;
- what should be returned when the condition evaluates to true,
- the condition itself, and
- what should be returned when the condition evaluates to false
The following example will illustrate
for num in range(0, 15, 3):
print(f"{num} is {'not ' if (num%2 != 0) else ''}even")
The for loop iterates over the multiples of 3 from 0 to 12, and prints out whether a number is even or not even. The output produced is
0 is even
3 is not even
6 is even
9 is not even
12 is even
Note the use of single quotes in the true- and false-part of the conditional expression. If we use double quotes, we will have a syntax error.
Calling functions and methods in f strings
We can call functions within f-strings, provided we surround the function call with curly braces.
def sq(x):
return x * x
print(f"The square of 5 is {sq(5)}")
When executed, this program produces
The square of 5 is 25
Similarly, we can put method calls in an f-string using the same syntax
str = "Hello f-strings!"
print(f"{str.upper()")
produces the following printout
HELLO F-STRINGS!
Referencing dictionary items in f strings
The following program accesses dictionary items within an f-string
person = {
'name': 'Daisy Johnson',
'workplace': 'SHIELD'
}
print(f"{person['name']} works for {person['workplace']}.")
the output is
Daisy Johnson works for SHIELD.
If we also enclosed the dictionary keys within double quotes, we would have had a syntax error. To avoid syntax errors, we need to use a different kind of quotation marks for the f-string and the dictionary keys.
Using python f strings with objects
Let us repurpose the previous example using objects.
class Person:
def __init__(self, name, workplace):
self.__name = name
self.__workplace = workplace
def __str__(self):
return f"{self.__name} works for {self.__workplace}."
person = Person('Daisy Johnson', 'SHIELD')
print(f"{person}")
The Person class has a __str__()
method that is automatically called whenever print encounters an instance of the Person class. The program produces the following output
Daisy Johnson works for SHIELD.
just like in the dictionary example.
Using f strings with format specifiers
Python f-strings can combined with format specifiers to express numbers, dates, floats and strings in a particular way. Format specifiers must be inside the curly braces, and separated from the expression using a colon. The following sections will discuss python f-string formatting.
Formatting floats in python f-strings
We can include float numbers within an f-string
num = 31.386
print(f"{num}")
produces the output
31.386
The precision (number of decimal places) can be specified after the dot character with an f suffix.
num = 31.386
print(f"{num: .2f}")
print(f"{num: .1f}")
produces the following output
31.39
31.4
Python will truncate and round the float number.
Specifying field-width in python f-strings
For whole numbers, we can specify the number of characters the final display should have. In the following example, we have specified that we want 0 to be used in filling empty spaces.
for num in range(1, 20, 4):
print(f"{num:0>3}")
produces the output
001
005
009
013
017
If we use z as the space-filling character, we would have
for i in range(1, 20, 4):
print(f"{i:z>3}")
Output:
zz1
zz5
zz9
z13
z17
Formatting dates in f-strings
We can also format date values in an f-string. The code fragment formats the current date and time
import datetime
time = datetime.datetime.now()
print(f"{time:%d-%m-%Y}") # uses the format dd-mm-yyyy
print(f”{time:%m-%d-%Y}”) # uses the format mm-dd-yyyy
produces the current date in two different formats
01-02-2022
02-01-2022
Using the format specifier %B instead of %m displays the full name of the month instead of the position of the month in the year.
print(f"{time:%B %d, %Y}")
displays
February 1, 2022
Justifying strings within python f-strings
By default, string values are justified to the left. However, left, right, or center justification options can be specified to control string justification. The below example justifies the contents of the variable str
using a character width of 46 (str
contains only 42 chars). The extra spaces are filled with *
(to help visualize what is going on)
str = "String formatting is great with f-strings!"
print(f"{str:*>46}") # Right justifies contents of str
print(f"{str:*<46}") # Left justifies contents of str
print(f"{str:*^46}") # Center justifies contents of str
the output will be
****String formatting is great with f-strings!
String formatting is great with f-strings!****
**String formatting is great with f-strings!**
Formatting numbers as different bases in f-strings
Python f-strings can also represent numbers in base 8 (octal), or base 16 (hexadecimal).
num = 29
print(f"{num} in octal is {num:o}") # displays num in octal
print(f"{num} in hexadecimal is {num:x}") # displays the number in hexadecimal
the output will be
29 in octal is 35
29 in hexadecimal is 1d
Conclusion
You can do many other things with f-strings. Python f-strings really makes string formatting less verbose, and easier to specify.
You can also learn about Self in Python.