Hoppa till huvudinnehållet

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.
· 5 min läs

Utforska med AI

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.

Kör och redigera koden från den här handledningen online

Kör kod

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"
Kör kod

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.")
Kör kod
Datacamp is an Educational company.
Kör kod

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.")
Kör kod
Datacamp is an Educational company.
Kör kod

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}")
Kör kod
25
Kör kod

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
Kör kod
## calling the function using f-string
name = "Datacamp"
print(f"{greet(name)}")
Kör kod
Hello, Datacamp
Kör kod

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()}")
Kör kod
Datacamp Is An Educational Company.
Kör kod

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.'
Kör kod
john = Sample("John", 19)

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

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}\"")
Kör kod
Hello, 'Datacamp'

Hello, "Datacamp"
Kör kod

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

f'{"Hello, Datacamp"}'
Kör kod
'Hello, Datacamp'
Kör kod
f"{'Hello, Datacamp'}"
Kör kod
'Hello, Datacamp'
Kör kod
f"""Hello, Datacamp"""
Kör kod
'Hello, Datacamp'
Kör kod
f'''Hello, Datacamp'''
Kör kod
'Hello, Datacamp'
Kör kod

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\"}")
Kör kod
  File "<ipython-input-60-b9a2502d6274>", line 1
    print(f"{\"Datacamp\"}")
         ^
SyntaxError: f-string expression part cannot include a backslash
Kör kod

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}}")
Kör kod
{Datacamp}
Kör kod

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

print(f"{{{{Datacamp}}}}")
Kör kod
{{Datacamp}}
Kör kod

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.")
Kör kod
John is 19 years old.
Kör kod

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.')
Kör kod
  File "<ipython-input-65-6849ff0810ae>", line 2
    print(f'{person['name']} is {person['age']} years old.')
                        ^
SyntaxError: invalid syntax
Kör kod

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

Ämnen

Relaterat

Handledning

Python String Tutorial