简体   繁体   English

python-在IPython中内联打印项目

[英]python - printing items inline in IPython

I need to print everything inline dynamically in a for loop in an IPython notebook. 我需要在IPython笔记本的for循环中动态内联打印所有内容。 I am using python 2.7 . 我正在使用python 2.7 I used the code: 我使用了代码:

for i in xrange(10):
   print "." , 
   #some computation and no print statement

and even used: 甚至使用:

for i in xrange(10):
   print "\b."
   #some computation and no print statement

but both of the above solutions doesn't seem to work in IPython notebooks. 但是上述两种解决方案似乎都无法在IPython笔记本中使用。

what I need is: .......... and what the above snippets are printing is: 我需要的是..........上面的摘要正在打印的是:

.
.
.
.
.
.
.
.
.
.

Any and every help is appreciated. 任何帮助都将受到赞赏。

This will work on both Python 2 and Python 3: 这将适用于Python 2和Python 3:

from __future__ import print_function

for i in range(10):
    print('.', end='')

You can also pass flush=True keyword argument to force it to flush the buffer instantly. 您还可以传递flush=True关键字参数来强制其立即刷新缓冲区。

You can also overwrite a previous line using '\\r' , her's a simple example: 您还可以使用'\\r'覆盖前一行,这是一个简单的示例:

import time

for i in range(10):
    time.sleep(0.2)
    print('\r{} / 10'.format(i + 1, 10), end='')

how about 怎么样

from __future__ import print_function
for i in xrange(10):
   print(".", end=' ')

You can do it using sys module. 您可以使用sys模块来完成。

import sys

for i in xrange(10):
    sys.stdout.write(".")

The print function is a wrapper which converts the object to string and formats the output. print功能是一个包装器,可将对象转换为string并格式化输出。

You can do exactly the same thing doing: 您可以做完全一样的事情:

print('.' * 10)

If you need a for loop you can assing the end variable to the print method like this: 如果需要for循环,可以将end变量赋给print方法,如下所示:

for i in range(10):
   print('.', end="")

I may not understand your question but have you tried to use: 我可能不明白您的问题,但您尝试使用以下方法:

print "."*10

You would get: 您将获得:

..........

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM