0

I'm trying to print a line in python 3 that will change as the program goes on. For example, if I try:

import time
for i in range(0,10):
    print('Loading' + '.'*i)
    time.sleep(0.5)

I get:

Loading.
Loading..
Loading...

and so on. Can I make it that the previous line changes and gets another '.' added to it instead of printing a new one? Of course, I could do:

import time, os
for i in range(0,10):
    os.system('cls')
    print('Loading' + '.'*i)
    time.sleep(0.5)

but that causes problems of its own. I know this question has been asked before, but all the answers given to it for some reason don't work. Doing something like:

import time
for i in range(0,10):
    print('Loading' + '.'*i, end="\r")
    time.sleep(0.5)

doesn't change anything, and replacing "\r" with " " just makes python not print anything for a while and then print out the whole row. What am I doing terribly wrong?

Vladimir Shevyakov
  • 1,886
  • 4
  • 15
  • 29

3 Answers3

2
import time
print('Loading', end='.')
for i in range(0,10):
    print('', end=".")
    time.sleep(0.5)

see explanation of end syntax and working example.

Paul Gowder
  • 2,079
  • 1
  • 17
  • 30
  • Doing `print('.', end='')` is more intuitive imo, just omitting the newline. – Felk Dec 01 '15 at 02:03
  • @Felk you're probably right about that. – Paul Gowder Dec 01 '15 at 02:04
  • That just doesn't print out anything for about 5 seconds, then I get 'Loading...........' in one print... – Vladimir Shevyakov Dec 01 '15 at 02:23
  • That's really weird. Does the second link in the answer (which goes to a runnable example) work for you? If it does, but it doesn't work in your interpreter, are you absolutely sure you're using python3? (Might also be a system clock or speed issue.) – Paul Gowder Dec 01 '15 at 02:42
  • The second link won't open: 'Secure connection to server failed.'. Not sure what the problem is there. I noticed that all the answers work for most people, but not for me - maybe some strange python glitch...? BTW I am using python 3.4 – Vladimir Shevyakov Dec 01 '15 at 02:45
  • On the second link, try the version w/o HTTPS, http://repl.it/B4m4/1 – Paul Gowder Dec 02 '15 at 00:52
1

You can use a carriage return \r to rewrite the current line like this:

import time
for i in range(50):
    print("Loading" + "."*i, end="\r")
    time.sleep(0.1)
Felk
  • 6,165
  • 1
  • 27
  • 51
0

You could use the ANSI clear screen escape character as

print(chr(27) + "[2J")
fcortes
  • 92
  • 2
  • 7