Applications
Formatters are generally used to Organize Data. Formatters can be seen in their best light when they are being used to organize a lot of data in a visual way. If we are showing databases to users, using formatters to increase field size and modify alignment can make the output more readable.
Example: To demonstrate the organization of large data using format()
Python3
# which prints out i, i ^ 2, i ^ 3, # i ^ 4 in the given range # Function prints out values # in an unorganized manner def unorganized(a, b): for i in range (a, b): print (i, i * * 2 , i * * 3 , i * * 4 ) # Function prints the organized set of values def organized(a, b): for i in range (a, b): # Using formatters to give 6 # spaces to each set of values print ( "{:6d} {:6d} {:6d} {:6d}" . format (i, i * * 2 , i * * 3 , i * * 4 )) # Driver Code n1 = int ( input ( "Enter lower range :-\n" )) n2 = int ( input ( "Enter upper range :-\n" )) print ( "------Before Using Formatters-------" ) # Calling function without formatters unorganized(n1, n2) print () print ( "-------After Using Formatters---------" ) print () # Calling function that contains # formatters to organize the data organized(n1, n2) |
Output :
Enter lower range :-
3
Enter upper range :-
10
------Before Using Formatters-------
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561
-------After Using Formatters---------
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.