# Formatting Output¶

In C Language, we had printf() function to display a formatted string to stdout. We also had format specifiers like %s for string, %d for integers and so on…

In Python, there are many ways to format a string, We shall have a look at each way.

Python provides ‘%’ as String formatting operator, which has to be used with C style format specifiers. General usage of this operator is as follows.

result = format_string % collection_of_items


Now Let’s see the Formatting Operator in action

In [16]:

'8 = %d , 8.5 = %.1f, name = %s, 3 = %04d' % (8,8.5,'Ravi',3)

Out[16]:

'8 = 8 , 8.5 = 8.5, name = Ravi, 3 = 0003'


There is one more way to format, without the hassle of remembering the format specifiers. You can use format() method of the current string. Same output of above example can be obtained as follows

In [18]:

'8 = {}, 8.5 = {}, name = {}, 3 = {:04}'.format(8,8.5,'Ravi',3)

Out[18]:

'8 = 8, 8.5 = 8.5, name = Ravi, 3 = 0003'


If the number of items to be formatted goes long, it would become hard to remember their positions. You can name each entry in format string, and refer to them in the call to format() as shown below. Note that the order of items can be changed now as the items are only referred by name.

In [19]:

'8 = {a}, 8.5 = {b}, name = {c}, 3 = {d:04}'.format(a=8,c='Ravi',d=3,b=8.5)

Out[19]:

'8 = 8, 8.5 = 8.5, name = Ravi, 3 = 0003'


Note

• In C and other related languages, '' is used to refer character and "" is used to refer string. But in Python, both refer to string. In Python single character is also a string
• Know more about Python String Formatting at PyFormat