简体   繁体   中英

How to replace text on python shell

I would like to make a program that will print out number values. I want it to display the number, then replace it with another number. A little like this:

val = 0
for looper in range(1, 10):
   val += 1
   print (val)
   #Code to replace old number to new number

Thanks for helping!

If you want in-place update of the number, you can use \\r.

import sys

val = 0
for looper in range(1, 10):
    val += 1
    sys.stdout.write("\r%d" % (val))
    sys.stdout.flush()
    time.sleep(1) # sleep added so that you can see the effect

Seems like you're looking for something to replace output in sys.stdout .

This is limited without using external libraries but you can do something like this:

import sys
import time

for number in xrange(10):
    # put number in 'stdout'
    sys.stdout.write(str(number))
    # empty stdout (by default it waits for a new line)
    sys.stdout.flush()
    # display the number for some time
    time.sleep(1)
    # go back to beginning of input to override existing output
    sys.stdout.write('\r')

我认为您正在将回车符与time.sleep(ms)一起使用“ \\ r”

On Python 3, @Teemu Kurppa's answer could be written as:

import time

for i in range(1, 11):
    print(i, end='\r', flush=True)
    time.sleep(1)

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