简体   繁体   中英

How to replace a printed line in Python 3

I am trying to make a sort of stop watch thing, just to try and learn some different stuff.

The problem is that I don't know how to make it so when you print what the time is, it just replaces what time you currently have printed.

For example if the time was:

HMS: 0 0 1

I would want it to display

HMS: 0 0 2

Without having to print a new line, so it would look like it is just counting up so to speak. I've it doing this in a way by printing new lines but it still shows a sort of movement which makes it clear that there are new lines being printed.

Here is my code as it is now, feel free to run it and your get what I mean: http://notepad.cc/woupodi42

Any ideas would be appreciated even better if they apply directly to this problem :)

There is an overload of print () that will do this. Combine this with [\\r][2] to move the cursor to the start of the line before writing each.:

import time
for x in range(10):
    print('\r H M S 0 0 ' + str(x), end='')
    time.sleep(1)

OR

for x in range(10):
    print('\r H M S 0 0 {}'.format(x), end='')
    time.sleep(1)

Hint for you, you need sys.stdout.write with \\r :

import sys, time
>>> for x in range(10):
...     sys.stdout.write('%d\r' % x)
...     sys.stdout.flush()
...     time.sleep(1)
... 

Use the end parameter to specify a "\\r" as the line ending.

for x in range(10):
    print('\r H M S 0 0 ' + str(x), end="\r")
    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