Last answered:

28 Apr 2021

Posted on:

07 Apr 2021

0

Resolved: Benefit of f-string vs variable

What is the benefit of using the f-string compared to just using the variable there?
For example: I've tried the same code with
    print(name, 'has been added.')
and it gave the same result.
Thanks

2 answers ( 1 marked as helpful)
Instructor
Posted on:

27 Apr 2021

4

Hi Stephan,

You have rightfully observed that using a simple print statement is going to produce the same result.
This means that, in this case, it is irrelevant whether we choose to use an f-string or not.
------------
F-strings become really useful when you want to embed a Python expression inside a string (so-called '(literal) string interpolation').
As you have found out, the following are absolute equivalent:

name = 'Stephan'
print(name, 'has been added.')
print(f'{name} has been added')

However, inside the curly brackets you could include a much more sophisticated expression without having to
define new variables. That is, you could do computations implicitly and plug the result right into the string.
One example could be a mathematical expression - observe how f-strings omit the need to define 2 additional variables.

import math
radius = int(input("Enter radius:" ).strip())
print(f'The circle with radius {radius} has an area of {math.pi * radius * radius} and circumference of {2 * math.pi * radius}')

In this lies the elegance of f-strings - they allow things to be written in a fast and concise manner.
------------
Best,
A. The 365 Team

Posted on:

28 Apr 2021

0

Hey Atanas,

thanks for the detailed answer. Very helpful!

Best,
Stephan

Submit an answer