在Python的同一行上有多个打印 [英] multiple prints on the same line in Python
问题描述
我想运行一个脚本,该脚本基本上显示如下输出:
I want to run a script, which basically shows an output like this:
Installing XXX... [DONE]
当前,我先打印Installing XXX...
,然后再打印[DONE]
.
Currently, I print Installing XXX...
first and then I print [DONE]
.
但是,我现在想在同一行上打印Installing xxx...
和[DONE]
.
However, I now want to print Installing xxx...
and [DONE]
on the same line.
有什么想法吗?
推荐答案
您可以使用print
语句执行此操作,而无需导入sys
.
You can use the print
statement to do this without importing sys
.
def install_xxx():
print "Installing XXX... ",
install_xxx()
print "[DONE]"
print
行末尾的逗号阻止print
发出新行(您应注意,输出末尾会有多余的空格).
The comma on the end of the print
line prevents print
from issuing a new line (you should note that there will be an extra space at the end of the output).
Python 3解决方案
由于以上内容在Python 3中不起作用,因此您可以改为这样做(同样,无需导入sys
):
The Python 3 Solution
Since the above does not work in Python 3, you can do this instead (again, without importing sys
):
def install_xxx():
print("Installing XXX... ", end="", flush=True)
install_xxx()
print("[DONE]")
打印功能接受默认值为"\n"
的end
参数.将其设置为空字符串可防止其在行尾发布新行.
The print function accepts an end
parameter which defaults to "\n"
. Setting it to an empty string prevents it from issuing a new line at the end of the line.
这篇关于在Python的同一行上有多个打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!