Python String format
Now, we are going to learn about string formatting using the format method. The thing here is that we can make use of the format method, to format the string, and now we are going to see how we can do that. With the help of this method, we can format the specified values, and insert them into the string’s placeholders (format fields).
Here, the placeholder is defined by using the curly brackets. Basically, we will talk more about the placeholders soon, but first of all, Let’s have a look at a simple example, through which we can get an idea about using the format method.
Python String format() Method
As you can see in the above program, we are taking two user inputs, the name and the age of the user, and then in the print statement, we are printing a simple message, which says Hello, my name is whatever name, and I am whatever age years old. Now the thing is that the name and age are going to be user inputs.
So, if we have the output of the above program, it would be something like this –
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, in the first placeholder, we have the name, and in another placeholder, we have the age input. So, we can say that the brackets here, would be replaced with the objects that we are passing to the format method. So, we can have the placeholder as empty curly brackets, and also, we can specify the numbered indexes or even the named indexes. Let’s try these too.
As you can see, in the above program, we have specified the numbered indexes in the curly brackets. Here, 0 is for the name, and 1 is for the age. You can also try to interchange them, like 1 in the first placeholder, and 0 in the second one, and that change would reflect in the output as well. We basically use a number in the brackets, to specify the position of the object passed into the format method.
If we try to run the above program again, there is going to be no change in the output.
As specified earlier, we can have named indexes as well, so now, Let’s have a look at them as well.
As you can see, in the above program, we have the named indexes, where username is for name, and the userage is for age, and we have specified it like that. Again, if we try to run the above program, there would be no changes in the output.
We can use the format method for string formatting. It is very easy, and very useful. Also, we would use the method, as and when required in our programs too.