Python: Output Formatting

In Python, We can present output of a program in several ways , data can be printed in a human-readable form, or written to a file for future use. Sometimes user often wants more control over the formatting of output than simply printing space-separated values.

There are many ways to format output.

  •  Use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark.
  • The str.format() method of strings help a user to get a fancier Output.
  • User can do all the string handling by using string slicing and concatenation operations to create any layout that user wants. The string type has some methods that perform useful operations for padding strings to a given column width.

1. Using String modulo operator(%) 

 % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format as in C language string to be applied to the right argument. The modulo operator % is overloaded by the string class to perform string formatting. It is often called a string modulo operator.


print("Integer : %3d, Float : %6.2f" % (2, 05.44))

Output: Integer : 2, Float : 5.44

2. Using format method

This method of strings requires more manual effort. We can use {} to mark where a variable will be substituted and can provide detailed formatting directives, but the we also needs to provide the information to be formatted. This method lets us concatenate elements within an output through positional formatting.


print('{0} and {1} is {2}'.format('Python', 'C', 'Programming Language')) 

Output: Python and C is Programming Language

3. Using String Method

The output is formatted by using String method by String slicing and concatenations. Through these methods, output can be formatted in exclusive way. Some of the methods are str.rjust() , str.centre() and str.ljust()

  • str.rjust(): It can align the sentence towards right side.
  • str.centre(): It helps sentence to move towards the center.
  • str.ljust(): It moves the sentence towards the left by this string function.


stmt_1 = "Welcome to Python"

print ("By Using str.rjust() ")  
print (stmt_1.rjust(40, '*')) 
print ("By Using : ")  
print (, '*'))  
print ("By Using str.ljust() : ")  
print (stmt_1.ljust(30, '*'))


By Using str.rjust() 
***********************Welcome to Python
By Using : 
****************Welcome to Python*****************
By Using str.ljust() : 
Welcome to Python*************