# Generic output formatting in Python

PythonServer Side ProgrammingProgramming

When printing the results of processing some data in python we may need to output them in certain appealing format or with some mathematical precision. In this article we will see what are the different options using which we can output the results.

## Using format

In this approach we use the in-built function called format. We use {} for placeholders of values that will be supplied by format. By default the positions will be filled in the same sequence of values coming from format function. But we can also force the values in terms of positions starting with 0 as index.

## Example

weather = ['sunny','rainy']
day = ['Mon','Tue','Thu']
print('on {} it will be {}'.format(day[0], weather[1]))
print('on {} it will be {}'.format(day[1], weather[0]))
print('on {} it will be {}'.format(day[2], weather[1]))
# Using positions
print('on {0} it will be {1}'.format(day[0], weather[0]))
print('It will be {1} on {0}'.format(day[2], weather[1]))

Running the above code gives us the following result −

## Output

on Mon it will be rainy
on Tue it will be sunny
on Thu it will be rainy
on Mon it will be sunny
It will be rainy on Thu

## Using %

This approach is more suitable for mathematical expressions. We can handle the number of decimal places to be displayed or print only the decimal part of a float. We can also convert the given numbers to octal or exponential values as in scientific notation.

## Example

# Print decimals
print("Average age is %1.2f and height of the groups %1.3f" %(18.376, 134.219))
# Print integers
print("Average age is %d and height of the groups %d" %(18.376, 134.219))
#
# Print octal value
print("% 2.7o" % (25))
# print exponential value
print("% 7.4E" % (356.08977))

Running the above code gives us the following result −

## Output

Average age is 18.38 and height of the groups 134.219
Average age is 18 and height of the groups 134
0000031
3.5609E+02

## String Alignment

We can align the outputs which are strings by using the string functions ljust,rjust or center. Besides the input string they can also take in another value which is used for padding the alignment.

## Example

strA = "Happy Birthday !"
# Aligned at center
print(strA.center(40, '~'),'\n')
# Printing left aligned
print(strA.ljust(40, 'x'),'\n')
# Printing right aligned
print(strA.rjust(40, '^'),'\n')

Running the above code gives us the following result −

## Output

~~~~~~~~~~~~Happy Birthday !~~~~~~~~~~~~
Happy Birthday !xxxxxxxxxxxxxxxxxxxxxxxx
^^^^^^^^^^^^^^^^^^^^^^^^Happy Birthday !
Published on 28-Dec-2020 11:05:20