Sunday, June 7, 2020

Output formatting in Python Print Function

Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning
We can also format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

No comments:

Post a Comment