How to use print() In Python

The print() function is used to display any message or output of processes carried out in Python. This function can be used to print strings or any object. But, before printing the object that is not of string type, print() converts it to a string. The string can be formatted either with the parameters of this method itself or using the rest of the methods covered in this article. The separator parameter (sep) of this function can help to display the desired symbol in between each element being printed. 

Example: Printing the swaps in each iteration while arranging a list in ascending order

Python3




# initialize the list
li = [1, 4, 93, 2, 3, 5]
  
print("Swaps :")
  
# loop for arranging
for i in range(0, len(li)):
  
    for j in range(i+1, len(li)):
  
        # swap if i>j
        if li[i] > li[j]:
            temp = li[j]
            li[j] = li[i]
            li[i] = temp
  
            # print swapped elements
            print(li[i], li[j], sep="<--->")
  
print("Output :", li)


Output

Swaps :
2<--->4
4<--->93
3<--->4
4<--->93
5<--->93
Output : [1, 2, 3, 4, 5, 93]

How to use string formatters in Python ?

The output displayed as a result of a program should be organized in order to be readable and understandable. The output strings can be printed and formatted using various ways as listed below.

  1. Using print()
  2. Using format specifiers.
  3. Using format() method.
  4. Using formatted string literal (f-string).

This article covers the first three methods given above.

Similar Reads

Using print()

The print() function is used to display any message or output of processes carried out in Python. This function can be used to print strings or any object. But, before printing the object that is not of string type, print() converts it to a string. The string can be formatted either with the parameters of this method itself or using the rest of the methods covered in this article. The separator parameter (sep) of this function can help to display the desired symbol in between each element being printed....

Using format specifiers

...

Using format() method

The format specifiers are the ones that we use in languages like C-programming. Python does not have a printf() as in C, but the same functionality is provided here. The modulo operator (‘%’) is overloaded by the string class for formatting the output. The % operator formats the set of variables contained within a tuple. If multiple format specifiers are chained, then the first specifier acts on the 0th element in the tuple, the second acts on 1st  element in the tuple and so on. The format specifiers are given in the table below....

Using f-string

...