0

Ok, I ask this question on behalf of someone else but I would also like to know if and how it is possible.

Let's say you have a given line of code producing the string

Time left: 4

Is there any way how I can then after this string has been printed edit the value of the "4" and change it to a "3" and then reprint the new string on the same line so Time left: 4 is replaced with Time left: 3 without causing a new line to be printed.

I hope you understand the question I did my best to explain it.

Kieran Lavelle
  • 426
  • 1
  • 4
  • 21
  • 1
    It'll be worth starting by looking at: https://pypi.python.org/pypi/progressbar/2.2 – Jon Clements Sep 11 '13 at 15:48
  • 1
    And here too http://stackoverflow.com/questions/4897359/output-to-the-same-line-overwriting-previous-output-python-2-5 (there's a python3 solution) – Samuele Mattiuzzo Sep 11 '13 at 15:49
  • @SamueleMattiuzzo ahh - that's the one I was trying to find... only progress bar sprang to mind though :) – Jon Clements Sep 11 '13 at 15:53
  • @Kieran: I would like to ask that you modify the question to 'How to alter a string after it has been *displayed*'. After a string has been *printed*, a small bottle of paint is required. – JS. Sep 12 '13 at 16:53

3 Answers3

6

Print a carriage return (\r), and make sure that your print statement is not writing a newline by adding end='' to the print arguments. After each print, make sure you flush stdout using sys.stdout.flush(). For example:

import time
import sys

for i in range(4, 0, -1):
    print('\rTime left:', i, end='')
    sys.stdout.flush()
    time.sleep(1)

On Python 2.x where print is a statement instead of a function, just add a trailing comma to prevent the newline:

import time
import sys

for i in range(4, 0, -1):
    print '\rTime left:', i,
    sys.stdout.flush()
    time.sleep(1)
Andrew Clark
  • 180,281
  • 26
  • 249
  • 286
2

One method is printing the backspace escape character (\b), which will will move the text cursor one character back; however, it is your responsibility to print something afterward to replace the text.

For example, if the current text in the terminal is Time left: 4 and you print "\b", the user will see nothing has changed. However, if you print "\b5", it will replace it with 5.

TND
  • 251
  • 1
  • 5
1
3>> for i in range(5, 0, -1):
...   print('\rTime left: {}      '.format(i), end='', flush=True)
...   time.sleep(1)
... 
Time left: 1      

(note: the output will actually be changing on your system :P )

Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283