Output Formatting in Python

Introduction

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.

Syntax:

%<flag><width><precision><type>

 

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))

Output:

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.

Example:

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))

Output:

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

Program:

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, '#'))

 

Output:

Using string method

Leave a comment

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