String Interpolation with f-strings in Python

If you need to concatenate a string and another type, you have to do typecasting when using the print function as explained in Type casting in Python.

So to convert age to a string you make str(age) in order to print a phrase using the + sign.

name = 'Bob'
weight = 80

print('My name is ' + name + ' and I weight ' + str(weight) + ' kg')
My name is Bob and I weight 80 kg

But that is not the best way to handle situations like this.

The best solution is to use String Interpolation, also called f strings.

Let’s first see how our example looks like using string interpolation.

name = 'Bob'
weight = 80

print(f'My name is {name} and I weight {weight} kg')
My name is Bob and I weight 80 kg

Notice the f at the beginning signaling to the interpreter that we are going to use interpolation, the presence of this f is the reason why this is also called f strings.

After the f you start your string, as usual, using quotes.

The key difference is that when you want to evaluate an expression like using the value of a variable, you just put them inside curly braces.

This is a simpler and more comfortable way to write very complex strings and you don’t have to worry about type conversion using type casting.