
About this article
Most of the time, a sample print()
statement might lead to messy code. And sometimes you do not need a logger to handle the job. Python offers different output options to deal with your string outputs. Here are a few
Formatting strings
1. Using %s in statements
print("Some text %s some text %s some text " %(str1,str2))
str1
and str2
takes the place of %s
and %s
in that order

You can even do mathematical operations in string outputs .

2. Formatting using f-prefix
We can write the same code using the f-string method .

It overcomes the limitation that %s has – you cannot specify an order (‘easily’) . So when you are using {variable_name}
you embed these in the desired parts of your statement and naturally overcome the ‘order-problem’
3. Aligning the output neatly using f-prefix
You can use the :>
, :<
or :^
option in the f-format to left align, right align or center align the text that you want to format.

After formatting the alignment of output text …

4. Using the format keyword
We can use the fortmat()
string function in python to output the desired text in the order we want.

Formatting numbers
Now extending the formatting using f keyword
( look at the piece above ) , lets try to use that in numbers, particularly involving decimals ( float )
1.Restricting the number of digits after the decimal point
eg: if i want to restrict the value of pi ( to the 2nd or 3rd decimal )

Normally, we would get this as a result

Now by formatting the number, we can restrict the number of decimals to 2 digits ….

or to 3 digits …

2. Formatting the output in pandas data-frames
To take it a little further, if you want to display the numbers in a particular format in your dataframe, when using pandas
you can use the pd.options.display
to show the way you want it. Here is an example of how numbers are displayed , before and after you enable the options.display
settings.
Lets take an example –
We are reading a file test.csv
and displaying the contents. We see that the length column has 6 decimal places displayed.

If we are interested in only displaying 2 decimal places, we can change it using the pd.options.display
attribute. Below is the output of the dataframe after the formatting is applied.

Note : Here on , for all the pandas displays ( even for other data-frames), only 2 decimal points will be displayed. If you want to set it back to 4 or 5 decimal points , you will have to set the format back to which ever format you want. Till then it will continue to display only 2 decimal points.
3. Formatting the output in numpy
Numpy has settings to change the decimal point precision to a desired one.
np.set_printoptions(precision=2)
Lets see the output as an extension to the previous example from pandas .
