在 Python 中的同一行上打印多个 [英] multiple prints on the same line in Python

查看:41
本文介绍了在 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):

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

打印函数接受一个 end 参数,默认为 " ".将其设置为空字符串可防止它在行尾发出新行.

The print function accepts an end parameter which defaults to " ". Setting it to an empty string prevents it from issuing a new line at the end of the line.

这篇关于在 Python 中的同一行上打印多个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆