F-Strings in Python

Python F-Strings

What are f-strings?

F-strings (formatted strings) are a recent addition to Python that offer a more intuitive and efficient way to format strings. They make it easier to insert variable values and expressions inside the text.

In this article, we will explore what f-strings are, how they work, and how they can make our lives easier.

Difference between f-strings and concatenation

Concatenation is the joining of two or more strings into a single string. String concatenation is done using the addition operator (+) or the join() method.

Example

name = "Osvaldo"
age = 42

message = "Olá, o meu nome é " + name + "e tenho " + age + " anos."
print(message)

But then we get this error:

TypeError: can only concatenate str (not "int") to str

This means we messed up, because as I said initially, concatenation joins strings, and what we have in the previous example is a string “Osvaldo” and an integer 42. How can we solve this?

We can always convert the data type to a string, like this:

message = "Olá, o meu nome é " + name + "e tenho " + str(age) + " anos."

Or we can use concatenation on steroids, f-strings.

To use f-strings, simply add the letter f before the string, and then any variable should be represented between {}.

Example

name = "Osvaldo"
age = 42

message = f"Olá, o meu nome é {name} e tenho {idade} anos."
print(message)

Output

Olá, o meu nome é Osvaldo e tenho 42 anos.

I hope this helps

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *

pt_PT