Tutorials  /  Python

Python f-strings - String Formatting Guide

Ccentron Redaktion · February 2024 ·4 min read ·Python, Tutorial

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.
Code
>>> 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.

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

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Python f-strings examples

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

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

Code
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.

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

Code
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.

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

Output:

Code
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.

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

Code
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.

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


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

Output:

Code
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.

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

6. Lambda expressions with f-strings

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

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

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

Output:

Code
Lambda Example: 20.45
Lambda Square Example: 25

7. f-strings miscellaneous examples

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

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

Output:

Code
quoted string
{ 40 }
{40}

Summary

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

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren