Let's presume we have a simple problem like to calculate a surface area code is:
slength = 10
swidth = 9
area = len * wid
print ("Surface area is " + area)
Obviously this will give error:
TypeError: can only concatenate str (not "int") to str
Hence, we will change to have:
slength = 10
swidth = 9
area = slength * swidth
print ("Surface area is " + str(area))
The idea with f string is that it helps to write in better way expression from print function from above example. Means it help in writing that concatenated string more concise.
Referring to "Surface area is " + str(area) we can write it easier with f string. There are two elements important for f string:
So, our example is:
slength = 10
swidth = 9
area = slength * swidth
print (f"Surface area is {area}")
Some observations:
Code is now:
slength = 10
swidth = 9
area = slength * swidth
print (f"Surface area is {area}, the length is {slength} and the width is {swidth}” )
Attention: once adding other text and variabiles, don’t forget to move the right " at the end means it need to be
print (f"Surface area is {area}, the length is {slength} and the width is {swidth}" )
and not
print (f"Surface area is {area}", the length is {slength} and the width is {swidth} )
Running the example: