Python f-strings – String Formatting Guide

Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498. It’s also called literal string interpolation.

Why do we need f-strings?

Python provides various ways to format a string. Let’s quickly look at them and what are the issues they have.

  • % formatting – great for simple formatting but limited support for strings, ints, doubles only. We can’t use it with objects.
  • Template Strings – it’s very basic. Template strings work with keyword arguments like dictionary only. We are not allowed to call any function and arguments must be strings.
  • String format() – Python String format() function was introduced to overcome the issues and limited features of %-formatting and template strings. However, it’s too verbose. Let’s look at its verbosity with a simple example.

>>> age = 4 * 10
>>> 'My age is {age}.'.format(age=age)
'My age is 40.'

Python f-strings works almost similar like format() function but removes all the verbosity that format() function has. Let’s see how easily we can format the above string using f-strings.

>>> f'My age is {age}'
'My age is 40.'

Python f-strings examples

Let’s look at a simple example of f-strings.

name = 'Pankaj'
age = 34

f_string = f'My Name is {name} and my age is {age}'

print(f_string)
print(F'My Name is {name} and my age is {age}')  # f and F are same

name = 'David'
age = 40

# f_string is already evaluated and won't change now
print(f_string)

Output:

My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34

Python executes statements one by one and once f-string expressions are evaluated, they don’t change even if the expression value changes. That’s why in the above code snippets, f_string value remains same even after ‘name’ and ‘age’ variable has changed in the latter part of the program.

1. f-strings with expressions and conversions

We can use f-strings to convert datetime to a specific format. We can also run mathematical expressions in f-strings.

from datetime import datetime

name = 'David'
age = 40
d = datetime.now()

print(f'Age after five years will be {age+5}')  # age = 40
print(f'Name with quotes = {name!r}')  # name = David
print(f'Default Formatted Date = {d}')
print(f'Custom Formatted Date = {d:%m/%d/%Y}')

Output:

Age after five years will be 45
Name with quotes = 'David'
Default Formatted Date = 2018-10-10 11:47:12.818831
Custom Formatted Date = 10/10/2018

2. f-strings support raw strings

We can create raw strings using f-strings too.

print(f'Default Formatted Date:\n{d}')
print(fr'Default Formatted Date:\n {d}')


Output:

Default Formatted Date:
2018-10-10 11:47:12.818831
Default Formatted Date:\n 2018-10-10 11:47:12.818831

3. f-strings with objects and attributes

We can access object attributes too in f-strings.

class Employee:
    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n

    def __str__(self):
        return f'E[id={self.id}, name={self.name}]'


emp = Employee(10, 'Pankaj')
print(emp)

print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')

Output:

E[id=10, name=Pankaj]
Employee: E[id=10, name=Pankaj]
Name is Pankaj and id is 10

4. f-strings calling functions

We can call functions in f-strings formatting too.

def add(x, y):
    return x + y


print(f'Sum(10,20) = {add(10, 20)}')

Output:

5. f-string with whitespaces

If there are leading or trailing whitespaces in the expression, they are ignored. If the literal string part contains whitespaces then they are preserved.

>>> age = 4 * 20
>>> f'   Age = {  age   }  '
'   Age = 80  '

6. Lambda expressions with f-strings

We can use lambda expressions inside f-string expressions too.

x = -20.45
print(f'Lambda Example: {(lambda x: abs(x)) (x)}')

print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')

Output:

Lambda Example: 20.45
Lambda Square Example: 25

7. f-strings miscellaneous examples

Let’s look at some miscellaneous examples of Python f-strings.

print(f'{"quoted string"}')
print(f'{{ {4*10} }}')
print(f'{{{4*10}}}')

Output:

Summary

That’s all for python formatted strings aka f-strings. Python f-strings – String Formatting Guide

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: