Formatting using the Formatted string literal (f-string)
Now, we are going to have a look at something, which is called the formatted string literal, or the f – string. The formatted string literals, or the f – strings, let us include the value of the python expression inside the string, by prefixing the string with F, or f. Here as well, the expression would be written within the curly brackets.
Let’s have a look at a simple example, through which, we can get some idea about the formatted string literals.
Python F-String
As you can see, we have the name and the age as user inputs, and then we are trying to print a simple message as an output. Here, we have made use of the formatted string literal, as the string is prefixed by f. Here, the expression is written into curly brackets. So, we can have an idea of how the output is going to be. So, Let’s have a look at the output now.
Please enter your name: GyaniPandit
Please enter your age: 25
Hello, my name is GyaniPandit, and I am 25 years old
As you can see, the value of the name and age is there in the string. So, this way, we can make use of the formatted string literal, for formatting the string. As we can see, here, we are able to use the value of the different expressions in the string. Remember that we need to prefix the string with f or F.
So, this way, we have seen string formatting here. So, we can make use of the different ways, as and when required in our programs. You can explore the concept in more depth.