Python F-String - Formatting Strings in Python With F-String
Python F-String - Formatting Strings in Python With F-String
Python f-string
last modified July 6, 2020
Python f-string tutorial shows how to format strings in Python with f-string.
Python f-string
Python f-string is the newest Python syntax to do string formatting. It is available since Python 3.6.
Python f-strings provide a faster, more readable, more concise, and less error prone way of
formatting strings in Python.
The f-strings have the f prefix and use {} brackets to evaluate values.
Format specifiers for types, padding, or aligning are specified after the colon character; for
instance: f'{price:.3}', where price is a variable name.
name = 'Peter'
age = 23
This is the oldest option. It uses the % operator and classic string format specifies such as %s and
%d.
Since Python 3.0, the format() function was introduced to provide advance formatting options.
Python f-strings are available since Python 3.6. The string has the f prefix and uses {} to evaluate
variables.
$ python formatting_string.py
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old
expressions.py
#!/usr/bin/env python3
bags = 3
apples_in_bag = 12
$ python expressions.py
There are total of 36 apples
print(f"{user['name']} is a {user['occupation']}")
$ python dicts.py
John Doe is a gardener
debug.py
#!/usr/bin/env python3
import math
x = 0.8
print(f'{math.cos(x) = }')
print(f'{math.sin(x) = }')
The example outputs the Sine and Cosine functions in the debug mode.
$ ./debug.py
math.cos(x) = 0.6967067093471654
math.sin(x) = 0.7173560908995228
multiline.py
#!/usr/bin/env python3
msg = (
f'Name: {name}\n'
f'Age: {age}\n'
f'Occupation: {occupation}'
)
print(msg)
The example presents a multiline f-string. The f-strings are placed between round brackets; each of
the strings is preceded with the f character.
$ python multiline.py
Name: John Doe
Age: 32
Occupation: gardener
call_function.py
#!/usr/bin/env python3
a = 3
b = 4
$ python call_fun.py
Max of 3 and 4 is 4
class User:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
def __repr__(self):
return f"{self.name} is a {self.occupation}"
print(f'{u}')
$ python objects.py
John Doe is a gardener
escaping.py
#!/usr/bin/env python3
To escape a curly bracket, we double the character. A single quote is escaped with a backslash
character.
$ python escaping.py
Python uses {} to evaludate variables in f-strings
This was a 'great' film
format_datetime.py
#!/usr/bin/env python3
import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
The example displays a formatted current datetime. The datetime format specifiers follow the :
character.
$ python format_datetime.py
2019-05-11 22:39
format_floats.py
#!/usr/bin/env python3
val = 12.3
print(f'{val:.2f}')
print(f'{val:.5f}')
$ python format_floats.py
12.30
12.30000
The output shows the number having two and five decimal places.
format_width.py
#!/usr/bin/env python3
for x in range(1, 11):
print(f'{x:02} {x*x:3} {x*x*x:4}')
The example prints three columns. Each of the columns has a predefined width. The first column
uses 0 to fill shorter values.
$ python format_width.py
01 1 1
02 4 8
03 9 27
04 16 64
05 25 125
06 36 216
07 49 343
08 64 512
09 81 729
10 100 1000
justify.py
#!/usr/bin/env python3
s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'
print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')
We have four strings of different length. We set the width of the output to ten characters. The
values are justified to the right.
$ python justify.py
a
ab
abc
abcd
format_notations.py
#!/usr/bin/env python3
a = 300
# hexadecimal
print(f"{a:x}")
# octal
print(f"{a:o}")
# scientific
print(f"{a:e}")
$ python format_notations.py
12c
454
3.000000e+02