F String In Python

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:

  •  first in front of the string we put f means we will have f"Surface area is "

  • second between " " we can write directly variables but those should be between curly braces i.e. "Surface area is " + str(area)  will be f"Surface area is {area}" 

So, our example is: 

slength = 10

swidth = 9

area = slength * swidth

print (f"Surface area is {area}")

Some observations:

  • There is no space between f and "Surface area is {area}" means it is f"Surface area is {area}"    and not   f "Surface area is {area}".

  • There is no need for str conversion function for area variable, conversion is performed basically by curly braces and/or "f". Means f string does all.
  • We can add further other text and/or use many curly braces. We can write for example:
    print (f"Surface area is {area}", the length is {slength} and the width is {swidth}" )

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: 

F string run example