Formatting of Strings in Python – New method V/S Old method
In this tutorial, we will be looking at how strings are formatted in accordance to wish of the user and in the demand of solution. In Python, the string formatting is still unknown to many people and many still ignore and fail to recognize the essence of string formatting. So today let’s take a look over it and see its applications in various areas.
String formatting in Python
Earlier we use the “%” symbol to format the strings which is a slightly inefficient method. . Now in updated versions of python an inbuilt method format() is used , which is very versatile and powerful tool.
Now let us look at each area application seperately.
Default printing of Strings as specified in Python
Str="{} {} {}".format('code','speedy','pavitra')
Printing in a specific order with the help of symbols in Python
Str="{f} {b} {l}".format(b='speedy',l='pavitra',f='code')
Printing in a specific order by the use of digits in Python
Str="{0} {1} {2}".format('code','speedy','pavitra')
Output:
code speedy pavitra
The binary representation of Number in Python
Str="{0:b}".format(10)
Output: 10000
Exponential representation of Number in Python
Str="{0:e}".format(165.6458)
Output: 1.656458r+02
Rounding off to decimal places in Python
Str="{0:.5f}".format(1/3)
Output: 0.33333
For left, right and center alignment of the text we can use the symbols “<“, “>”, “^” within the curly braces.
Str="{:<left_alignwidth}{:^centre_width}{:>right_alignwidth}".format('code','speedy','pavitra')
Now lets look over to the old style method i.e using “% ” operator.
For example, let us see the use of this operator in the illustration of rounding off discussed above without the use of inbuilt format() method.
Integer=12.34453
print("Integer is %2.3f" % Integer)
Output
>>> 12.344
Please also refer to ,
Leave a Reply