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
                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.
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.
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
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.
import os
print "hello"
print "dude"
if <your condition to bye print >
    os.system('clear')
    print "bye"
                        As an alternative to
os.system('clear')
you can also use
print "\n" * 100
The value 100 can be changed to what you require
In  Python 3:
print("hello", end='\r', flush=True)
print("dude", end='\r', flush=True)
print("bye", end='\r', flush=True)
Output:
bye
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With