Skip to main content
HomeAbout PythonLearn Python

f-string Formatting in Python

Learn about the f-string formatting technique in Python 3.6. In this tutorial, you'll see what advantages it offers and go through some example use cases.
Jul 2019  · 5 min read

1. Introduction

What is string formatting?

String formatting is attractively designing your string using formatting techniques provided by the particular programming language. We have different string formatting techniques in Python. We are now going to explore the new f-string formatting technique.

f-string evaluates at runtime of the program. It's swift compared to the previous methods.

f-string having an easy syntax compared to previous string formatting techniques of Python. We will explore every bit of this formatting using different examples.

Run and edit the code from this tutorial online

Open Workspace

1.1. Syntax

Every f-string statement consists of two parts, one is character f or F, and the next one is a string which we want to format. The string will be enclosed in single, double, or triple quotes.

Let's see the syntax.

## we can also use F, '', ''''', """"""'
f"string"

In place of string, we have to place our sentence which is going to format.

2. Displaying Variables

We previously use the str.format() method mostly to format the strings. But, the time has changed we have a new method to make our efforts twice as fast.

The variables in the curly { } braces are displayed in the output as a normal print statement. Let's see an example.

## declaring variables
name = "Datacamp"
type_of_company = "Educational"

## enclose your variable within the {} to display it's value in the output
print(f"{name} is an {type_of_company} company.")
Datacamp is an Educational company.

We have got the values of the variables in the output. See, it's easy. We can also replace the f with F as well.

## declaring variables
name = "Datacamp"
type_of_company = "Educational"

## enclose your variable within the {} to display it's value in the output
print(F"{name} is an {type_of_company} company.")
Datacamp is an Educational company.

f is either lower or upper it'll work the same.

3. Expressions

What if we can evaluate expressions like arithmetic, function calls, etc., in a string? It's cool right! Yeah! It's very, very exciting to use expressions inside a string. f-string allows us to evaluate expressions inside the string.

Just put the expression inside { } to evaluate. f-string evaluates it at runtime of the program. It's an excellent feature which saves you time and code.

Let's see examples of the different types of expressions.

## arithmetic expression
print(f"{5 * 5}")
25

We can also call functions inside the { }. Let's define a function greet() and call it in the f-string

def greet(name):
    return "Hello, " + name
## calling the function using f-string
name = "Datacamp"
print(f"{greet(name)}")
Hello, Datacamp

In the same way, we can also call the predefined methods. Let's see.

## calling the 'title' method which makes the first letter of every word upper
string = "datacamp is an educational company."
print(f"{string.title()}")
Datacamp Is An Educational Company.

What else can we do with the f-string? Are we able to display the object? Yes, we can. It's the same as when we show the output of the variables.

class Sample:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    ## this method will be called when we print the object
    def __str__(self):
        return f'{self.name} is {self.age} years old.'
john = Sample("John", 19)

## it'll wake up the __str__() method
print(f"{john}")
John is 19 years old.

4. Special Characters

What if we want to display special characters like {}, \', \"?, which are internally used by Python for special meaning. Can we use escape character inside the f-string? Let's see the answers to these questions.

4.1. Quotations

We can use any quotation marks {single or double or triple} in the f-string. We have to use the escape character to print quotation marks. The f-string expression doesn't allow us to use the backslash. We have to place it outside the { }.

Let's see it by examples.

name = "Datacamp"

## displaying single quotations
print(f"Hello, \'{name}\'")

print()

## displaying double quotations
print(f"Hello, \"{name}\"")
Hello, 'Datacamp'

Hello, "Datacamp"

Let's see other types of quotations in f-strings.

f'{"Hello, Datacamp"}'
'Hello, Datacamp'
f"{'Hello, Datacamp'}"
'Hello, Datacamp'
f"""Hello, Datacamp"""
'Hello, Datacamp'
f'''Hello, Datacamp'''
'Hello, Datacamp'

We can also include { } inside the three quotes as well.

You can't use the backslashes inside the { } in f-string. You'll get an error if they are included inside { }.

print(f"{\"Datacamp\"}")
  File "<ipython-input-60-b9a2502d6274>", line 1
    print(f"{\"Datacamp\"}")
         ^
SyntaxError: f-string expression part cannot include a backslash

4.2. Braces

We have to use a double set of braces to print the braces using f-string. Let's see an example.

print(f"{{Datacamp}}")
{Datacamp}

If you want to display two sets of braces using f-string, then you have to use four sets of braces.

print(f"{{{{Datacamp}}}}")
{{Datacamp}}

5. Dictionaries

We have to be a bit careful while dealing with dictionary keys inside the f-string. You have to use a different quotation to the dictionary key and f-string. You are not permitted to use the same quotations for a dictionary key as if it was an f-string.

person = {"name": "John", "age": 19}
print(f"{person['name']} is {person['age']} years old.")
John is 19 years old.

You are not allowed to use it as follows in the case of dictionaries.

person = {"name": "John", "age": 19}
print(f'{person['name']} is {person['age']} years old.')
  File "<ipython-input-65-6849ff0810ae>", line 2
    print(f'{person['name']} is {person['age']} years old.')
                        ^
SyntaxError: invalid syntax

Conclusion

I hope you learn something new in Python by reading this tutorial. To learn more about strings and previous formatting techniques head over this tutorial on Datacamp. Also, check out DataCamp's Regular Expressions in Python course.

Happy Coding :)

Topics

Python Courses

Certification available

Course

Introduction to Python

4 hr
5.4M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Mastering the Pandas .explode() Method: A Comprehensive Guide

Learn all you need to know about the pandas .explode() method, covering single and multiple columns, handling nested data, and common pitfalls with practical Python code examples.
Adel Nehme's photo

Adel Nehme

5 min

Python NaN: 4 Ways to Check for Missing Values in Python

Explore 4 ways to detect NaN values in Python, using NumPy and Pandas. Learn key differences between NaN and None to clean and analyze data efficiently.
Adel Nehme's photo

Adel Nehme

5 min

Seaborn Heatmaps: A Guide to Data Visualization

Learn how to create eye-catching Seaborn heatmaps
Joleen Bothma's photo

Joleen Bothma

9 min

Test-Driven Development in Python: A Beginner's Guide

Dive into test-driven development (TDD) with our comprehensive Python tutorial. Learn how to write robust tests before coding with practical examples.
Amina Edmunds's photo

Amina Edmunds

7 min

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

See MoreSee More