当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How can I replace a printed line with a new printed line?

问题描述:

What I am looking to do is replace a print statement with a new print statement. In layman's terms, I want the console to print Downloading... and then replace it with Downloading...done! as soon as the downloading finishes. I have tried this answer but it just prints some garbage and then the print statement on a new line. I am using Python 3. Thanks in advance!

网友答案:

use end="" in the first print, default value of end is a new line but you can change it by passing your own value:

print("Downloading...",end="")
#your code here
print("Done!")

output:

Downloading...Done!

help on print:

In [3]: print?
Type:       builtin_function_or_method
String Form:<built-in function print>
Namespace:  Python builtin
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.
网友答案:

A simple example:

import time
print("Downloading... ", end='')
time.sleep(3)
print("done.")

you can also replace a part of the line printet before using "\r":

import time
print("Downloading... ", end='')
time.sleep(3)
print("\r.............. done.")

This of course only works as long as you don't print a newline anywhere before the carriage return character.

网友答案:
print ("Print this line, and print a newline")
print ("Print this line, but not a newline", end="")

http://www.harshj.com/2008/12/09/the-new-print-function-in-python-3/

网友答案:

If you'd like a interactive ..., i.e. it grows, you could do something like this. Just change the conditional in the while with something more fitting, or even use while True and a if and break inside the loop.

>>> import time
>>> def dotdotdot():
...     print("Downloading", end="")
...     a = 0
...     while a < 10:
...         print(".", end="")
...         time.sleep(1)
...         a += 1
...     print("done!")
...
>>> dotdotdot()
Downloading..........done!
分享给朋友:
您可能感兴趣的文章:
随机阅读: