Python | Formatting the output

Python Methods and Functions

There are several ways of presenting the results of a program, the data can be printed in human readable form or written to a file for future use. Sometimes the user often needs more control over the formatting of the output than just printing the values ​​separated by spaces. There are several ways to format the output.

  • To use String method str.format () helps the user get more graceful output
  • The user can do all the string processing using the string slice and concatenation operations to create any layout you want. The string type has several methods that perform useful operations to fill strings to a given column width.

Formatting output using the String operator modulo (%):
The % operator can also be used to format strings. It interprets the left argument in the same way as a printf () style format string to apply to the right argument. There is no printf () function in Python, but the functionality of the ancient printf is contained in Python. To this end, the modulo operator % is overloaded with the string class to perform string formatting. Therefore, it is often called the modulo (or sometimes even modulo) operator. 
The modulo string operator (% ) is still available in Python (3.x) and is widely used by the user. But now the old formatting style has been removed from the language.

# Python program showing how to use
# string modulo operator (%) for printing
# Favorite output

  
# print integer and floating point value

print ( "Geeks:% 2d, Portal:% 5.2f" % ( 1 , 05.333 )) 

 
# print integer value

print ( " Total students:% 3d, Boys:% 2d " % ( 240 , 120 ))

 
# output octal value

print ( "% 7.3o" % ( 25 ))

 
# output exponential value

print ( "% 10.3E" % ( 356.08977 ))

Output:

 Geeks: 1, Portal: 5.33 Total students: 240, Boys: 120 031 3.561E + 02 

In our example, there are two of them: "% 2d" and "% 5.2f". The general syntax for a format placeholder is:

% [flags] [width] [. Precision] type 

Let`s take a look at the placeholders in our example.

  • The first placeholder "% 2d" is used for the first component of our tuple, which is integer 1. The number will be printed with 2 characters. Since 1 consists of only one digit, the output is padded with 1 leading spaces.
  • The second "% 8.2f" — this is a description of the format for a floating point number. Like other placeholders, it is entered with the % character. This is followed by the total number of digits that the string should contain. This number includes the decimal point and all digits, that is, before and after the decimal point.
  • Our floating point number 05.333 must be formatted with 5 characters. The decimal part of the number or precision is set to 2, that is, the number after the "." In our placeholder. Finally, the last "f" of our placeholder means "float".

Formatting the output using a formatting method:
The format () method has been added to Python (2.6). The string formatting method requires more manual labor. The user uses {} to mark where the variable will be substituted and can provide detailed formatting directives, but the user must also provide formatting information. This method allows us to combine elements in the output through positional formatting. For example — 
Code 1:

# Show Python program
# using the format () method

  
# using the format () method

print ( `I love {} for "{}!" ` . format ( `Geeks` , ` Geeks` ))

 
# using the format () method and referencing
# object position

print ( `{0} and {1}` < / code> . format ( `Geeks` , ` Portal` ))

 

print ( `{1} and {0}` . format ( `Geeks` , ` Portal ` ))

Output:

 I love Geeks for "Geeks!" Geeks and Portal Portal and Geeks 

The brackets and characters within them (called format fields ) are replaced with objects passed to the format () method. The number in brackets can be used to indicate the position of the object passed to the format () method.

Code 2:

# Show Python program
# use format () method

 
# combining positional and keyword arguments

print ( `Number one portal is {0}, {1}, and {other} .`

. format ( `Geeks` , ` For` , other = `Geeks` ))

  
# using the format () method with number

print ( "Geeks: {0: 2d}, Portal: {1: 8.2f} "

format ( 12 , 00.546 ))

 
# Change positional argument

print ( "Second argument: {1: 3d}, first one: {0: 7.2f} " .

  format ( 47.42 , 11 ))

 

print ( "Geeks: {a: 5d}, Portal: {p: 8.2f}" .

  format (a = 453 , p = 59.058 ))

Output:

 Number one portal is Geeks, For, and Geeks. Geeks: 12, Portal: 0.55 Second argument: 11, first one: 47.42 Geeks: 453, Portal: 59.06 

The following usage diagram shows how the formatting method works for positional parameters:

Code 3:

# Python program for
# show format () yes
# used in the dictionary

 

tab = { ` geeks` : 4127 , `for` : 4098 , `geek` : 8637678 }

 
# using format () in the dictionary

print ( `Geeks: {0 [geeks]: d}; For: {0 [for]: d}; `

  ` Geeks: {0 [geek]: d} ` . format (tab))

 

data = dict (fun = " GeeksForGeeks " , adj = "Portal" )

 
# using format () in the dictionary

print ( "I love {fun} computer {adj}" . format ( * * data))

Output:

 Geeks: 4127; For: 4098; Geeks: 8637678 I love GeeksForGeeks computer Portal 

Formatting output using the String method:
This output is formatted using slice and string concatenation operations. The string type has several methods that help you format the output in a more elegant way. Some of the methods that help in formatting the output: str.rjust () , str.centre ()

# Python program for
# format the output using
# string () method

 

cstr = "I love pythonengineering"

 
# Print centered
# line with fillchr

print ( "Center aligned string with fillchr:"

print (cstr.center ( 40 , `#` )) 

 
# Left-aligned
# padded string & quot; - & quot;

print ( "The left aligned string is: "

print (lstr.ljust ( 40 , `-` ))

 
# Print a line by right margin
# with & quot; - & quot; addition

print ( "The right aligned string is: "

print ( rstr.rjust ( 40 , `-` ))

Output:

 Center aligned string with fillchr: ########## I love pythonengineering ########## The left aligned string is: I love pythonengineering -------------------- The right aligned string is: -------------------- I love pythonengineering 




Get Solution for free from DataCamp guru