Tutorial

Python f-strings - PEP 498 - Literal String Interpolation

Published on August 3, 2022
author

Pankaj

Python f-strings - PEP 498 - Literal String Interpolation

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 is introduced to have minimal syntax for string formatting. The expressions are evaluated at runtime. If you are using Python 3.6 or higher version, you should use f-strings for all your string formatting requirements.

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: Sum(10,20) = 30

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 insidef-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:

quoted string
{ 40 }
{40}

That’s all for python formatted strings aka f-strings.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: PEP-498, Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 7, 2021

Hi Pankaj, I can’t seem to use logging module along with f-string formatting. I get an pylint error: use lazy % formatting in logging (logging-fstring-interpolation) I’m unable to figure out the right reason for it. Any suggestions?

- Srivatsava Guduri

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 11, 2020

    Great codes you write!

    - Parakshit

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Become a contributor for community

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      DigitalOcean Documentation

      Full documentation for every DigitalOcean product.

      Resources for startups and SMBs

      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

      Get our newsletter

      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

      New accounts only. By submitting your email you agree to our Privacy Policy

      The developer cloud

      Scale up as you grow — whether you're running one virtual machine or ten thousand.

      Get started for free

      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

      *This promotional offer applies to new accounts only.