打印到同一行而不是新行? [英] Print to the same line and not a new line?

查看:50
本文介绍了打印到同一行而不是新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想做和这个家伙做的相反的事情......呵呵.

Basically I want to do the opposite of what this guy did... hehe.

Python脚本:每次向 shell 打印新行而不是更新现有行

我有一个程序可以告诉我它还有多远.

I have a program that is telling me how far along it is.

for i in some_list:
    #do a bunch of stuff.
    print i/len(some_list)*100," percent complete"

因此,如果 len(some_list) 为 50,我会将最后一行打印 50 次.我想打印一行并不断更新该行.我知道我知道这可能是你整天阅读的最蹩脚的问题.我就是想不通我需要输入谷歌才能得到答案的四个词.

So if len(some_list) was 50, I'd get that last line printed 50 times over. I want to print one line and keep updating that line. I know I know this is probably the lamest question you'll read all day. I just can't figure out the four words I need to put into google to get the answer.

更新!我尝试了 mvds 的建议,这似乎是正确的.新代码

Update! I tried mvds' suggestion which SEEMED right. The new code

print percent_complete,"           \r",

完成百分比只是一个字符串(我是第一次抽象,现在我试图成为文字).现在的结果是它运行程序,直到程序结束后才打印任何内容,然后在一行且仅一行打印100%完成".

Percent complete is just a string (I was abstracting the first time now I an trying to be literal). The result now is that it runs the program, doesn't print ANYTHING until after the program is over, and then prints "100 percent complete" on one and only one line.

没有回车(但有逗号,mvds 建议的一半)它直到最后什么都不打印.然后打印:

Without the carriage return (but with the comma, half of mvds' suggestion) it prints nothing until the end. And then prints:

0 percent complete     2 percent complete     3 percent complete     4 percent complete    

等等.所以现在的新问题是,在程序完成之前,它不会打印逗号.

And so on. So now the new issue is that with the comma it doesn't print until the program is finished.

使用回车而不使用逗号,它的行为与两者都没有完全相同.

With the carriage return and no comma it behaves the exact same as with neither.

推荐答案

这叫做回车,或者 \r

使用

print i/len(some_list)*100," percent complete         \r",

逗号阻止打印添加换行符.(空格将使行与先前的输出保持清晰)

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

另外,不要忘记以 print "" 结束以获得至少一个最终的换行符!

Also, don't forget to terminate with a print "" to get at least a finalizing newline!

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

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