f-Strings in Python

Working with strings can be difficult, especially when you need to print the output in a particular format using variables.

In this blog post, you will learn how to use f-Strings in Python for formatting strings easily.

Let's look at some of the examples:

Without using f-string

a = 5
b = 10
result = "The Sum of " + str(a) + " and " + str(b) + " is equal to " + str(a+b)
print(result)
The Sum of 5 and 10 is equal to 15

Notice you need to convert integers to strings, and spaces have been added in the result string which makes it a bit difficult to write.

Using f-string

a = 5
b = 10
result = f"The Sum of {a} and {b} is {a+b}"
print(result)
The Sum of 5 and 10 is equal to 15

Now again check the result string, how easy it becomes to use variables inside a string, no need to do string to integer conversion, and spaces are simply added.

To use an f-String, your string should begin with f, inside quotes string can be written while using {} for passing in variable values.

That's all for now, use f-strings from now onward and save yourself some time.