In Python Programming, sometimes wee need to get some parts of a string from another place. This can be a result of a calculation or a value form a database. For such information that will come from outside, we use python string format method.
We use this method with the help of curly brackets {}. In the string, we put these characters (curly brackets) instead of the value that we will get. After that, we use python string format method and the printed string contains both our string and the gotten value.
Below, you can find a basic example for the usage of this method.
Here, we ask from the user to enter a price value. After that we convert this value to integer value. In the third line, we use curly brackets in the place of where we put the formatted value. Laslt, we will print the message with the formatted value.
We can also use different values that show how to convert the value. For example, if we would like to add two zeros after zero for a number value, we can use “:.2f” in the curly brackets like {:.2f}.
We can add more values with python string format method. To divide these value, we use comma in the format method brackets.
Would you like to learn how to find Python String Length?
If you do not use index numbers, then the format is done in order. If you use index values, then, the format is done according to the index values. For example, 0 means the first operator of format, 1 is the second and so on. Let’s given an example to understand this better.
Here, as you can see above, we can use the order of the variables as we want. The output of this python code will be:
Now, let’s use strings instead of numbers as formatted value.
The output will be:
We can use names in the curly brackets of the python string format method. But at this time, we need to specify the name with a value in the format method brackets. So, we can get the similar result of the above code with the below code also.
The code’s output will be:
As you can see here, we can use python string format method for various reasons. It is a very useful method in python programming that allow us to put dynamic values in a string.
Leave a Reply