What is Python Output Formatting?
What is Output Formatting in Python?
A program's output can be shown in a variety of ways, including printing data in a human-readable manner, saving data to a file for later use, or presenting data in another way.
Users frequently want more output formatting choices than just printing space-separated values. There are several output formatting options.The output of a program can be shown in a variety of ways, including printing it in a human-readable manner or saving it to a file for later use. More flexibility over the output formatting than merely publishing space-separated values may be desired by the user.
To utilize formatted string literals, precede the initial quotation mark or triple quotation mark with f or F.The str.format() function of strings assists a user in obtaining a nicer result. Users may construct any layout they desire by utilizing string slicing and concatenation techniques to accomplish all of the string processing. The string type includes a few methods that may be used to pad strings to specific column width.
Formatting output using String modulo operator(%)
String formatting can also be done with the percent operator. It treats the left parameter as if it were a printf()
-style format string to be applied to the right.
Example
print("abc : % 2d, Portal : % 5.2f" %(1, 05.333))
print("Total students : % 3d, Boys : % 2d" %(240, 120))
print("% 7.3o"% (25))
print("% 10.3E"% (356.08977))
Output
Formatting Output Using Format Method in Python
Python 2.6 introduced the format()
function. The string formatting approach necessitates greater manual work. Users can indicate where a variable will be substituted and offer precise formatting directions, but they must also supply the data to be prepared.
Example
tab = {'abc': 4127, 'for': 4098, 'python': 8637678}
print('abc: {0[abc]:d}; For: {0[for]:d}; '
'python: {0[python]:d}'.format(tab))
data = dict(fun ="abcforPython", adj ="Python")
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
cstr = "I love python"
print ("Center aligned string with fillchr: ")
print (cstr.center(40, '$'))
print ("The left aligned string is : ")
print (cstr.ljust(40, '-'))
print ("The right aligned string is : ")
print (cstr.rjust(40, '-'))
Output
It’s Quiz Time!
