[英]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!
用外行的话来说,我希望控制台打印“正在
Downloading...
,然后将其替换为“正在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.
我已经试过这个答案,但它只是打印一些垃圾,然后在新行上打印print语句。 I am using Python 3. Thanks in advance!
我正在使用Python 3。
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
使用end=""
, end
默认值是一个new line
但是您可以通过传递自己的值来更改它:
print("Downloading...",end="")
#your code here
print("Done!")
output : 输出 :
Downloading...Done!
help on print
: 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": 您还可以在使用“ \\ r”之前替换行printet的一部分:
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/ http://www.harshj.com/2008/12/09/the-new-print-function-in-python-3/
If you'd like a interactive ...
, ie 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. 只要改变的条件
while
更多的东西配件,甚至使用while True
和if
和break
环内。
>>> import time
>>> def dotdotdot():
... print("Downloading", end="")
... a = 0
... while a < 10:
... print(".", end="")
... time.sleep(1)
... a += 1
... print("done!")
...
>>> dotdotdot()
Downloading..........done!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.