There are a number of different ways to format output in Python. Let’s learn about those formatting techniques in this article.
Using string concatenation
Example 1:
By using string concatenation, we have to take care of spaces also. We are concatenating the output using + operator.
Example 2:
If we miss the spaces, the output is not displayed as we would expect. This is one of the drawbacks with this.
Using str.format() method
In str.format(), we can use {} to indicate where variable to be substituted.
Example 1:
In the below example, in the first curly brackets, the first variable ‘mango’ will be substituted and in the second curly brackets, ‘green’ will be substituted.
Example 2:
If we mention numbers in the curly brackets, it is used to refer to the position of the object passed to the str.format() method.
Example 3:
In str.format(), we can also pass the method to access the dictionary values.
Dictionary values can be accessed by d[key] or d.get(key)
Example 4:
We can mention the format specifier inside the curly brackets. It allows us to control the formatting of the values.
Like if we mention {:,.2f} →It indicates two decimal places. The values will be rounded to two decimal places.
Using formatted string literals (f-strings)
When we use f string formatting, we have to include ‘f’ before the opening quotation mark.
Here, we can mention expressions inside the curly brackets which will refer to variables or literal values.
Example 1:
In this example, variables are included inside the curly brackets.
Example 2:
In this example, a method to access dictionary values is given inside the curly brackets.
Example 3:
Inside the curly brackets, we can mention the string methods too. It will get evaluated and correct results will be displayed.
Example 4:
In this example, the expression is given inside the curly brackets {a*2}. The value of a is doubled and then the output is displayed.
Example 5:
Similarly, formatting the values can also be done. Here, in this example, we round off to two decimal places.
Only in the f string formatting can we include expressions.
Conclusion:
In this article, we have explored the different ways to format the output. I hope you all liked it. Thanks for reading!
AUTHOR:
Indhumathy Chelliah – SheCanCode Blog Squad