
Last chance! 50% off DataCamp Premium
Sale ends in
Buy Now
Kör och redigera koden från den här handledningen online
Kör kodEvery 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.
In place of string, we have to place our sentence which is going to format.
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.")
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.")
f is either lower or upper it'll work the same.
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.
We can also call functions inside the { }. Let's define a function greet() and call it in the f-string
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()}")
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.'
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.
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}\"")
Let's see other types of quotations in f-strings.
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 { }.
File "<ipython-input-60-b9a2502d6274>", line 1
print(f"{\"Datacamp\"}")
^
SyntaxError: f-string expression part cannot include a backslashWe have to use a double set of braces to print the braces using f-string. Let's see an example.
If you want to display two sets of braces using f-string, then you have to use four sets of braces.
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.")
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
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 :)
Handledning
Handledning
Handledning
Python Courses
Kurs
Bemästra grunderna i dataanalys med Python på bara fyra timmar. Denna onlinekurs introducerar Python-gränssnittet och utforskar populära paket.
Kurs
Dyk ner i data science med Python och lär dig analysera och visualisera dina data effektivt. Ingen kodningsvana eller färdigheter behövs.
Kurs
Lyft dina data science-färdigheter genom att skapa visualiseringar med Matplotlib och manipulera DataFrames med pandas.
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.