7

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
Dixit Singla
  • 2,540
  • 3
  • 24
  • 39

6 Answers6

5

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

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
3

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.

Cilyan
  • 7,883
  • 1
  • 29
  • 37
2
import os
print "hello"
print "dude"
if <your condition to bye print >
    os.system('clear')
    print "bye"
MONTYHS
  • 926
  • 1
  • 7
  • 30
2

As an alternative to

os.system('clear')

you can also use

print "\n" * 100

The value 100 can be changed to what you require

Arif Amirani
  • 26,265
  • 3
  • 33
  • 30
2

In Python 3:

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

Output:

bye
Omid Raha
  • 9,862
  • 1
  • 60
  • 64
1

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

Dixit Singla
  • 2,540
  • 3
  • 24
  • 39