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) |
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.
- Using print()
- Using format specifiers.
- Using format() method.
- Using formatted string literal (f-string).
This article covers the first three methods given above.