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

Python Courses

Introduction to Python

BeginnerSkill Level
4 hr
5.2M
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

10 Essential Python Skills All Data Scientists Should Master

All data scientists need expertise in Python, but which skills are the most important for them to master? Find out the ten most vital Python skills in the latest rundown.

Thaylise Nakamoto

9 min

The 7 Best Python Certifications For All Levels

Find out whether a Python certification is right for you, what the best options are, and the alternatives on offer in this comprehensive guide.
Matt Crabtree's photo

Matt Crabtree

18 min

A Complete Guide to Socket Programming in Python

Learn the fundamentals of socket programming in Python
Serhii Orlivskyi's photo

Serhii Orlivskyi

41 min

Textacy: An Introduction to Text Data Cleaning and Normalization in Python

Discover how Textacy, a Python library, simplifies text data preprocessing for machine learning. Learn about its unique features like character normalization and data masking, and see how it compares to other libraries like NLTK and spaCy.

Mustafa El-Dalil

5 min

Coding Best Practices and Guidelines for Better Code

Learn coding best practices to improve your programming skills. Explore coding guidelines for collaboration, code structure, efficiency, and more.
Amberle McKee's photo

Amberle McKee

26 min

Pandas Profiling (ydata-profiling) in Python: A Guide for Beginners

Learn how to use the ydata-profiling library in Python to generate detailed reports for datasets with many features.
Satyam Tripathi's photo

Satyam Tripathi

9 min

See MoreSee More