简体   繁体   中英

Overwrite the previous print value in 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

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

import os
print "hello"
print "dude"
if <your condition to bye print >
    os.system('clear')
    print "bye"

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.

As an alternative to

os.system('clear')

you can also use

print "\n" * 100

The value 100 can be changed to what you require

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

In Python 3 :

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

Output:

bye

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM