Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a printed line in Python 3

Tags:

python

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:

H M S: 0 0 1

I would want it to display

H M S: 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 :)

like image 465
deano3663 Avatar asked Oct 21 '25 03:10

deano3663


2 Answers

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)
like image 183
Justin R. Avatar answered Oct 23 '25 16:10

Justin R.


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)
like image 42
paullb Avatar answered Oct 23 '25 18:10

paullb