Python - Output Formatting

PythonServer Side ProgrammingProgramming

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

  • To 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.

Formatting output using String modulo operator(%)

The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format string to be applied to the right argument.

Example

 Live Demo

# string modulo operator(%) to print
# print integer and float value
print("Vishesh : % 2d, Portal : % 5.2f" %(1, 05.333))
# print integer value
print("Total students : % 3d, Boys : % 2d" %(240, 120))
# print octal value
print("% 7.3o"% (25))
# print exponential value
print("% 10.3E"% (356.08977))

Output

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

Formatting output using format method

The format() method was added in Python(2.6). Format method of strings requires more manual effort. User use {} to mark where a variable will be substituted and can provide detailed formatting directives, but user also needs to provide the information to be formatted.

Example

# show format () is used in dictionary
tab = {'Vishesh': 4127, 'for': 4098, 'python': 8637678}
# using format() in dictionary
print('Vishesh: {0[vishesh]:d}; For: {0[for]:d}; '
'python: {0[python]:d}'.format(tab))
data = dict(fun ="VisheshforPython", adj ="Python")
# using format() in dictionary
print("I love {fun} computer {adj}".format(**data))

Formatting output using String method

In this output is formatted by using string slicing and concatenation operations.

Example

 Live Demo

# format a output using string() method
cstr = "I love python"
# Printing the center aligned
# string with fillchr
print ("Center aligned string with fillchr: ")
print (cstr.center(40, '$'))
# Printing the left aligned string with "-" padding
print ("The left aligned string is : ")
print (cstr.ljust(40, '-'))
# Printing the right aligned string with "-" padding
print ("The right aligned string is : ")
print (cstr.rjust(40, '-'))

Output

Center aligned string with fillchr:
$$$$$$$$$$$$$I love python$$$$$$$$$$$$$$
The left aligned string is :
I love python---------------------------
The right aligned string is :
---------------------------I love python
raja
Published on 06-Aug-2020 12:15:29
Advertisements