Header Ads

Python Print

Print is one of the most basic function in python. As name suggests, Print function prints text to screen. Print statement was converted to print() function in python 3.PEP 3105 was proposed to make print a function.

Signature

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Explanation

Print function prints passed arguments separated by sep and ended by end to file flushing/not flushing buffer every time.
 
*objects means any number of python objects can be passed as (positional) arguments. print will print string representation of these objects.
 
sep = ' ' means sep is a keyword argument with default value of blank space. sep will be used as separator between printed objects.
 
end = '\n' means end is a keyword argument with default value new line character. End character will be printed at the end.
 
file=sys.stdout is another keyword argument which specifies where print will write text. Default file is sys.stdout which represent standard output(console or terminal) but it can be can be changed to any object implementing write(string) function.
 
flush is a keyword argument to control flushing of buffer. It takes boolean value. Default value False means buffer will not be flushed. print may not be writing output immediately to file and wait for buffer to be flushed when it is filled. When flush is True all content of output buffer will be flushed wo file immediately.


Documentation

https://docs.python.org/3/library/functions.html#print

Fun with print


Print in a new line



for num in xrange(1,10):
    print(num)

1
2
3
4
5
6
7
8
9
    

Print without new line

for num in xrange(1,10):
    print (num, end=' ')
    

1 2 3 4 5 6 7 8 9

    

Don't print spaces between words

print('hello','world' sep='')


helloworld
    

Pretty Print objects

Some python built in  objects are printed in a beautiful structure.
 
mylist=[1,2]
mydict={"name":"python"}
print(mylist)
print(mydict)
    

[1,2]
{"name":"python"}
    
But user defined classes are not pretty printed :).

class myclass:
      def __init__():
          self.mydata='python'
myobj=myclass()
print(myobj)
output:

<__main__ .myclass="" 0x0712345="" at="" instance="">
    
Make your objects pretty

class myclass:

      def __init__():

          self.mydata='python'

          pass    

      def __str__:

          return 'myclass:['+self.mydata+']'

          #return string that you want to print.

myobj=myclass()
print(myobj)
    
output:

myclass:[python]
    
For many operations python calls special methods automatically called Dunder or Double Underscore Methods or Data model methods. Print() calls __str__  to get string representation of object. We can override default __str__ to pretty print objects.

Print in place

Printing progress bar with python print.
We can print in place to create a progress bar in python3 we can use end='\r'.
\r is the carriage return character that takes the cursor to the first position. 
Argument end = '\r' will print carriage return at the end which will take the cursor to the first position of the current line. 
Subsequent print() will overwrite existing characters.

print('in progress [%d%%]'%progresspercent,end='\r') 
    

Flush Buffer 

Sometimes we want print() to immediately flush data to the output stream without buffering. 
For example, we want to print real-time progress to the output stream.If the output stream is buffered, print() will write to the buffer, the buffer may be flushed to stdout later. We can immediately flush buffer by setting flush=True. Flush will ensure that every progress is written immediately to stdout and avoid printing multiple progress lines due to buffering.

print('in progress [%d%%]'%progresspercent,end='\r',flush=True) 

Printing to a file


logfile=open('app.log','w')
print("Starting ....",file=logfile)



Please comment and give your feedback. We hope this article is useful for you.

No comments

Powered by Blogger.