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.
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.
# 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))
Vishesh : 1, Portal : 5.33 Total students : 240, Boys : 120 031 3.561E+02
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.
# 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))
In this output is formatted by using string slicing and concatenation operations.
# 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, '-'))
Center aligned string with fillchr: $$$$$$$$$$$$$I love python$$$$$$$$$$$$$$ The left aligned string is : I love python--------------------------- The right aligned string is : ---------------------------I love python