Overwrite the previous print value in python?

2020-07-10 01:08发布

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

标签: python
6条回答
虎瘦雄心在
2楼-- · 2020-07-10 01:18

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

查看更多
forever°为你锁心
3楼-- · 2020-07-10 01:31

As an alternative to

os.system('clear')

you can also use

print "\n" * 100

The value 100 can be changed to what you require

查看更多
Rolldiameter
4楼-- · 2020-07-10 01:32

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

查看更多
Emotional °昔
5楼-- · 2020-07-10 01:32

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.

查看更多
SAY GOODBYE
6楼-- · 2020-07-10 01:40

In Python 3:

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

Output:

bye
查看更多
Evening l夕情丶
7楼-- · 2020-07-10 01:43
import os
print "hello"
print "dude"
if <your condition to bye print >
    os.system('clear')
    print "bye"
查看更多
登录 后发表回答