How to create a F-String in Python

How to create an F-String in Python

F-string also known as formatted strings used for making a string a bit dynamic by inserting the values in it using variables or user input.

To understand F-strings better first we have to understand the concept of string formating which we can do using %s in a string, to format a string use %s wherever you want to replace the value with the values or variable provided at the end of the string.

Execute the below line of code in python

In the output %s is replaced with the value Lokesh provided at the end of the string. We can do the same with multiple values as well, to pass multiple values use a tuple starting with a % symbol as below.

With an increased number of values, this method becomes hectic and you won’t prefer it if you have to replace a higher number of values in a string as the readability of the string reduces with more values.

we can also use this method with variables as below.

There is another way of formatting a string called the .format string method where we won’t be using %s anymore, here we use {} wherever we need a replacement then all the places wherever we have {} are replaced with the values provided at the end inside .format method sequentially.

Here is one more fact we can add to this i.e. we can also impute values in any order for that we have to include sequence number inside the {} then it will pick up the values in the provided sequence as below

All of the above methods somehow reduce the readability of a string

and that is why it is preferred to use the F-String concept which increases the readability of the string and it’s an easy to use method.

F-String starts with f” ” wherein you may write any string inside the quotations, inside the quotes we may use {var/value/expression} to pass the parameter or impute value in the string, here is an example

One more fact about F-String is that we may pass any expression or function inside the string which makes it dynamic and expands the usage of this method.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.