Output formatting in Python

Output formatting in Python

Python Output formatting

There are several ways to show the output of a program, data or message 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. We can do this with several formatting types.

  • 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, you can change this according to your choice.
  • 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, which we have done lots of time in C language. Lets again come back to the Python, there is no printf() function but the functionality of the ancient printf is contained in Python. To this purpose, the modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is often called string modulo (or sometimes even called modulus) operator.
String modulo operator ( % ) is still available in Python(3.x) and user is using it widely. But nowadays the old style of formatting is removed from the language. You can choose according to your taste of coding.

And some of the basic things you can learn by yourself

Now lets see some piece of codes as an Example to more clearance.

# Python program showing how to use
# string modulo operator(%) to print
# fancier output
  
# print integer and float value
print("Code : % 2d, Portal : % 5.2f" %(1, 05.444)) 
  
# print integer value
print("Total programmers : % 3d, Boys : % 2d" %(220, 140))
  
# print octal value
print("% 7.3o"% (25))
  
# print exponential value
print("% 10.3E"% (356.08977))


output :

Code : 1, Portal : 5.44 Total programmers : 220, Boys : 140 031 3.561E+02

python coding,python ide,pep8,best python ide,python program,python ide windows,python basic programs,factorial program in python ,prime number program in python



There are two of those in our example: “%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, i.e. the integer 1. The number will be printed with 2 characters as you mentioned. As 1 consists only of one digits, the output is padded with 1 leading blanks.
  • The second one “%8.2f” is a format description for a float number. Like other placeholders, it is introduced with the character. This is followed by the total number of digits the string should contain. This number includes the decimal point and all the digits, i.e. before and after the decimal point.
  • Our float number 05.444 has to be formatted with 5 characters. The decimal part of the number or the precision is set to 2, i.e. the number following the “.” in our placeholder. Finally, the last character “f” of our placeholder stands for “float”.

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. This method lets us concatenate elements within an output through positional formatting. 

For Example –


Code 1:

# Python program showing 
# the use of format() method
  
# using format() method
print('I love {} "{}!"'.format('code', 'dudle'))
  
# using format() method and refering 
# a position of the object
print('{0} and {1}'.format('code', 'portal'))
  
print('{1} and {0}'.format('code', 'portal'))

output :

I love code"dudle!" code and portal portal and code

The brackets and characters within them (called format fields) are replaced with the objects passed into the format() method. A number in the brackets can be used to refer to the position of the object passed into the format() method.
I hope that you clear upto this. Lets move forward and see the another code.

code 2:

# Python program showing 
# a use of format() method
  
# combining positional and keyword arguments
print('best learning portal is {0}, {1}, and {other}.'
     .format('code', 'For', other ='dudle'))
  
# using format() method with number 
print("code :{0:2d}, Portal :{1:8.2f}".
      format(12, 00.546))
  
# Changing positional argument
print("Second argument: {1:3d}, first one: {0:7.2f}".
      format(47.42, 11))
  
print("code: {a:5d},  portal: {p:8.2f}".
     format(a = 451, p = 59.058))


output :

best learning portal is code, For, and dudle. code :12, Portal : 0.55 Second argument: 11, first one: 47.42 code: 451, portal: 59.06

The following diagram with an example usage shows how the format method works for positional parameters:

python coding,python ide,pep8,best python ide,python program,python ide windows,python basic programs,factorial program in python ,prime number program in python


code 3:

# Python program to 
# show format () is 
# used in dictionary
  
tab = {'code': 84209, 'dudle': 86740}
  
# using format() in dictionary
print('Code: {0[code]:d};
    'Dudle: {0[dudle]:d}'.format(tab))
  
data = dict(fun ="codedudle", adj ="portal")
  
# using format() in dictionary
print("I love {fun} computer {adj}".format(**data))

output :

Code: 84209; Dudle: 86740 I love codedudle computer portal

Formatting output using String method :

In this output is formatted by using string slicing and concatenation operations. The string type has some methods that help in formatting a output in an fancier way. Some of method which help in formatting a output are str.ljust()str.rjust()str.centre(), lets try this with some Examples -
# Python program to
# format a output using
# string() method
  
cstr = "I love codedudle"
    
# 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 codedudle########## The left aligned string is : I love codedudle-------------------- The right aligned string is : --------------------I love codedudle


In this i have covered the different output formats in Python. 



                  Basic print() function in Python            
                                          





 #fluent python
 #introduction to machine learning with python
 #python machine learning
 #deep learning with python
 #best way to learn python
 #learn python for data analysis free
 #learn python free
 #best sites to learn python
 #free python tutorial
 #best free online python course
 #python free online course

































Post a Comment

7 Comments

  1. Very much informative.Love your all post Sir

    ReplyDelete
  2. it is very helpful sir, thank you

    ReplyDelete
  3. Well represented....
    Very helpfull

    ReplyDelete
    Replies
    1. Thankyou ....stay connected for more posts

      Delete
  4. Output Formatting In Python >>>>> Download Now

    >>>>> Download Full

    Output Formatting In Python >>>>> Download LINK

    >>>>> Download Now

    Output Formatting In Python >>>>> Download Full

    >>>>> Download LINK U9

    ReplyDelete

If you have any doubt, Please let me know.