Output Formatting in Python


While printing the output on-screen one can format it the way they need.

Different ways to format output:

  • Using String modulo operator(%)
  • Using format method
  • Using string method


1.      Using String module operator(%)

Module operator(%) is old-style formatting technique used in coding. However, it is available in Python 3.x version also but is used in minimal scenarios as the old formatting style is removed.




Output Formatting in PythonProgram:

print("Integer: %2d, Floating number: %2.2f, Octal representation of 30: %7.3o, Exponential representation: %10.3E" % (3, 2.42256, 30, 450.456))


Using String module operator

2.      Using format method

The format() method provides the positional formatting of the output. It was introduced in Python 2.6. The braces {} is used to define the position of value to be substituted.


a = int(input("Enter the first number:"))

    b = int(input("Enter the second number:"))

    c = a + b

    print("The sum of {0} and {1} is {2}".format(a,b,c))


Using format method

The numbers in the brackets representations the position to place the values passed in the format method.

3.      Using string method

Python provides string methods to display the output in much ornamental way: The methods that can be used for formatting are:

  • ljust() : Left align
  • rjust() : Right align
  • centre() : Centre align


ip_str = "We are learning to format the output in Python!"

#Align string to right

print ("Align string to right: ")

print (ip_str.ljust(60, '#'))

#Align string to left

print ("Align string to left: ")

print (ip_str.rjust(60, '#'))

#Align string to centre

print ("Align string to centre: ")

print (ip_str.center(60, '#'))



Using string method


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.