F-String in Python

Hello Friends, In this segment we are going to discuss F-String in Python. In this segment, we shall know what is F-string, how it works, why we need to use this, everything about F-string.

So let us start with our first question of what is F-string, F-string is a type of string formatting although there are various ways already exist in python of string formatting. But some times those ways become more complicated when we do string formatting so the F-string is very easy to use in string formatting.

Why we need to use F-string in Python

Our second question is why we need to use F-string. We can understand it by visiting the example of string formatting so let us move to the example.

a = "mohit"
print("this is %s" %a)

In the above code, we used a variable in a string to print a variable’s value and the result of the above code is given below.

this is mohit

 

By seeing this code you can think that as many times we need to insert a variable we will have to use %s which can be complicated in the reading of code. Now take another example where we will use tuple for string formatting.

a = "Mohit"
b = "Tripathi"
c = "This is %s %s"%(a,b)
print(c)

In the above code, we have passed two variables in a string in tuple but here is also it becomes complicated during the reading of code. Below is the output of the code.

This is Mohit Tripathi

 

Now take a look at string formatting by F-string.

a = "Mohit"
b = "Tripathi"
print(f"this is {a} {b}")

Output:

this is Mohit Tripathi

In the above code, you can see that we pass two variables in a string by F-string where we used f”    {} {}  ” this statement tells the compiler that the statement is passed as  F-string and in {} braces we write variable you can use braces according to the variable we want to add in the string.

Also read:

Language Detector In Python

Desktop Notification In Python

Leave a Reply