Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite the previous print value in python?

Tags:

python

How can i overwrite the previous "print" value in python?

print "hello"
print "dude"
print "bye"

It will output:

hello
dude
bye

But i want to overwrite the value.

In this case the output will be:

bye
like image 659
Dixit Singla Avatar asked Feb 08 '14 13:02

Dixit Singla


People also ask

How do you overwrite a previous printed line in Python?

Simple Version One way is to use the carriage return ( '\r' ) character to return to the start of the line without advancing to the next line.

Can we override print function in Python?

Overloading print is a design feature of python 3.0 to address your lack of ability to do so in python 2. x. However, you can override sys. stdout.


6 Answers

Check this curses library, The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals. An example:

x.py:

from curses import wrapper
def main(stdscr):
    stdscr.addstr(1, 0, 'Program is running..')  
    # Clear screen
    stdscr.clear()  # clear above line. 
    stdscr.addstr(1, 0, 'hello')
    stdscr.addstr(2, 0, 'dude')
    stdscr.addstr(3, 0, 'Press Key to exit: ')
    stdscr.refresh()
    stdscr.getkey()

wrapper(main)
print('bye')

run it python x.py

like image 96
Grijesh Chauhan Avatar answered Sep 22 '22 15:09

Grijesh Chauhan


You can use sys.stdout.write to avoid the newline printed by print at each call and the carriage return \r to go back to the beginning of the line:

import sys
sys.stdout.write("hello")
sys.stdout.write("\rdude")
sys.stdout.write("\rbye")

To overwrite all the characters of the previous sentence, you may have to add some spaces.

On python 3 or python 2 with print as a function, you can use the end parameter:

from __future__ import print_function #Only python 2.X
print("hello", end="")
print("\rdude ", end="")
print("\rbye  ", end="")

Note that it won't work in IDLE.

like image 29
Cilyan Avatar answered Sep 20 '22 15:09

Cilyan


import os
print "hello"
print "dude"
if <your condition to bye print >
    os.system('clear')
    print "bye"
like image 42
MONTYHS Avatar answered Sep 22 '22 15:09

MONTYHS


As an alternative to

os.system('clear')

you can also use

print "\n" * 100

The value 100 can be changed to what you require

like image 35
Madhusoodan Avatar answered Sep 22 '22 15:09

Madhusoodan


In Python 3:

print("hello", end='\r', flush=True)
print("dude", end='\r', flush=True)
print("bye", end='\r', flush=True)

Output:

bye
like image 31
Omid Raha Avatar answered Sep 19 '22 15:09

Omid Raha


Best way is.

Write

   sys.stdout.flush()

After print.

Example:

import sys
sys.stdout.write("hello")
sys.stdout.flush()
sys.stdout.write("bye")

Output: bye

like image 26
Dixit Singla Avatar answered Sep 22 '22 15:09

Dixit Singla