0

For example:

x=0
while x!=10000:
  print(x)
  x += 1

this outputs:

0
1
2
3....

but i don't want it to create new lines. I want it to replace the previous number so that only the numbers change without it creating new lines, if that makes sense.

furas
  • 134,197
  • 12
  • 106
  • 148
  • 3
    `print( ..., end="\r")` it moves cursor to begining of current line instead of new line - and then you can write in the same place. – furas Jul 23 '20 at 10:11
  • BTW: see [tqdm](https://github.com/tqdm/tqdm) which uses this method to draw progress bar. – furas Jul 23 '20 at 10:13

1 Answers1

2

You can use \r instead of \n in print(..., end='\r') to move cursor to beginning of line and then you can write in the same place.

Minimal working code

import time

for x in range(100):
    print(x, end='\r')
    time.sleep(0.1)

I added time.sleep to slow down it.

If you have to write shorter text in place of longer text then you may have to add spaces at the end of text.

I'm not sure if all terminals/consoles respect \r.

Some terminals may use other codes to move cursor, clear clear, etc. These codes are used by modules like curses, npyscreen, urwid, asciimatics to create widgets in text mode.


BTW: If you want it to draw progress bar then see module tqdm

furas
  • 134,197
  • 12
  • 106
  • 148