The question is in the title.
问题在题目里。
I'd like to do it in python. What I'd like to do in this example in c:
我想用python来做。在这个例子中我想做的是
#include <stdio.h>
int main() {
int i;
for (i=0; i<10; i++) printf(".");
return 0;
}
Output:
输出:
..........
In Python:
在Python中:
>>> for i in xrange(0,10): print '.'
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print '.',
. . . . . . . . . .
In Python print
will add a \n
or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first build a string then print it. I'd like to know how to "append" strings to stdout
.
在Python打印中会添加一个\n或空格,我如何避免呢?这只是一个例子。不要告诉我我可以先建立一个字符串然后打印出来。我想知道如何向stdout添加字符串。
25 个解决方案
#1
1835
General way
import sys
sys.stdout.write('.')
You may also need to call
你可能还需要打电话
sys.stdout.flush()
to ensure stdout
is flushed immediately.
确保stdout立即被刷新。
Python 2.6+
From Python 2.6 you can import the print
function from Python 3:
从Python 2.6可以从Python 3导入打印函数:
from __future__ import print_function
This allows you to use the Python 3 solution below.
这允许您使用下面的Python 3解决方案。
Python 3
In Python 3, the print
statement has been changed into a function. In Python 3, you can instead do:
在Python 3中,print语句已被更改为函数。在Python 3中,您可以改为:
print('.', end='')
This also works in Python 2, provided that you've used from __future__ import print_function
.
如果您已经使用了__future__导入print_function,那么它也可以在Python 2中工作。
If you are having trouble with buffering, you can flush the output by adding flush=True
keyword argument:
如果您在缓冲方面有问题,可以通过添加flush=True关键字参数来刷新输出:
print('.', end='', flush=True)
#2
269
It should be as simple as described at this link by Guido Van Rossum:
它应该像圭多·范·罗瑟姆在这个链接中所描述的那样简单:
Re: How does one print without a c/r ?
没有信用证怎么打印?
http://legacy.python.org/search/hypermail/python-1992/0115.html
http://legacy.python.org/search/hypermail/python-1992/0115.html
Is it possible to print something but not automatically have a carriage return appended to it ?
是否可以打印某样东西,但不可以自动将回车附加到它上面?
Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline:
是的,在最后一个参数之后添加一个逗号来打印。例如,这个循环打印数字0。用空格隔开的线。注意添加最后换行的无参数“打印”:
>>> for i in range(10):
... print i,
... else:
... print
...
0 1 2 3 4 5 6 7 8 9
>>>
#3
157
Note: The title of this question used to be something like "How to printf in python?"
注意:这个问题的标题曾经类似于“如何在python中printf ?”
Since people may come here looking for it based on the title, Python also supports printf-style substitution:
由于人们可能会基于标题来寻找它,Python也支持printf样式的替换:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
And, you can handily multiply string values:
可以方便地将字符串值相乘:
>>> print "." * 10
..........
#4
83
Use the python3-style print function for python2.6+ (will also break any existing keyworded print statements in the same file.)
在python2.6+中使用python3风格的打印函数(也会在同一个文件中破坏任何现有的关键字打印语句)。
# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
print('.', end='')
To not ruin all your python2 print keywords, create a separate printf.py
file
为了不破坏所有的python2打印关键字,创建一个单独的printf。py文件
# printf.py
from __future__ import print_function
def printf(str, *args):
print(str % args, end='')
Then, use it in your file
然后,在你的文件中使用它
from printf import printf
for x in xrange(10):
printf('.')
print 'done'
#..........done
More examples showing printf style
更多显示printf样式的示例
printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000
#5
37
This is not the answer to the question in the title, but it's the answer on how to print on the same line:
这不是标题中问题的答案,但它是关于如何在同一条线上打印的答案:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
#6
20
The new (as of Python 3.0) print
function has an optional end
parameter that lets you modify the ending character. There's also sep
for separator.
新的(从Python 3.0开始)打印函数有一个可选的结束参数,允许您修改结束字符。还有sep用于分隔符。
#7
17
You can just add ,
in the end of print
function so it won't print on new line.
你可以在打印函数的末尾添加,这样它就不会在新行上打印了。
#8
13
Using functools.partial to create a new function called printf
使用functools。偏置以创建一个名为printf的新函数
>>> import functools
>>> printf = functools.partial(print, end="")
>>> printf("Hello world\n")
Hello world
Easy way to wrap a function with default parameters.
用默认参数包装函数的简单方法。
#9
13
print
function in python automatically generates a new line. You could try:
在python中打印函数自动生成一条新行。你可以试试:
print("Hello World", end="")
打印(“Hello World”,最后= " ")
#10
9
Code for Python 3.6.1
Python代码3.6.1
for i in range(0,10): print('.' , end="")
Output
输出
..........
>>>
#11
7
You can do it with end
argument of print. In python3 range() returns iterator and xrange() doesn't exist.
你可以用结束参数打印。在python3 range()中返回迭代器,xrange()不存在。
for i in range(10): print('.', end='')
#12
7
you want to print something in for loop right;but you don't want it print in new line every time.. for example:
你想要在for循环中打印一些东西,但是你不希望每次都在新的行中打印。例如:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print "hi"
但是你想让它像这样打印:嗨,嗨,你好,你好,对吗???? ?在打印“hi”后添加一个逗号
Example:
例子:
for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi
i在range(0,5)中:打印“hi”输出:hi hi hi hi hi hi hi hi hi hi hi hi hi
#13
7
You can try:
你可以尝试:
import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')
#14
6
In Python 3, printing is a function. When you call
在Python 3中,打印是一个函数。当你打电话
print ('hello world')
Python translates it to
Python翻译它
print ('hello world', end = '\n')
You can change end to whatever you want.
你可以改变任何你想要的东西。
print ('hello world', end = '')
print ('hello world', end = ' ')
#15
5
for i in xrange(0,10): print '.',
This will work for you. here comma (,) is important after print. Got help from : http://freecodeszone.blogspot.in/2016/11/how-to-print-in-python-without-newline.html
这对你有用。这里的逗号(,)在打印后很重要。从http://freecodeszone.blogspot.in/2016/11/how to printin -python-without newline.html获得帮助
#16
4
You can do the same in python3 as follows :
你可以在python3中这样做:
#!usr/bin/python
i = 0
while i<10 :
print('.',end='')
i = i+1
and execute it with python filename.py
or python3 filename.py
并使用python文件名执行它。py或python3 filename.py
#17
4
@lenooh satisfied my query. I discovered this article while searching for 'python suppress newline'. I'm using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn't want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn't cruncxed to a halt nor been sent to lunch on a merry infinite loop - as a plea to 'leave me be, I'm doing fine, but this may take some time.' interactive message - like a progress bar in text.
@lenooh满意我的查询。我在搜索“python抑制换行”时发现了这篇文章。我在树莓派上使用IDLE3开发Python 3.2 for PuTTY。我想在PuTTY命令行上创建一个进度条。我不希望页面滚动。我想要一条横线,让用户放心,这个程序并没有陷入停顿,也没有被发送到午餐的欢乐无限循环——作为一种请求,“离开我吧,我做得很好,但这可能需要一些时间。”互动信息——就像文本中的进度条。
The print('Skimming for', search_string, '\b! .001', end='')
initializes the message by preparing for the next screen-write, which will print three backspaces as ⌫⌫⌫ rubout and then a period, wiping off '001' and extending the line of periods. After search_string
parrots user input, the \b!
trims the exclamation point of my search_string
text to back over the space which print()
otherwise forces, properly placing the punctuation. That's followed by a space and the first 'dot' of the 'progress bar' which I'm simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.
打印('Skimming for', search_string, '\b!措施”,结束= ")初始化消息,准备下一个screen-write将打印三退格⌫⌫⌫擦掉,然后一段时间内,抹去了‘001’和扩展的时期。在search_string鹦鹉螺用户输入后,\b!将search_string文本的感叹号调整回print()所强制的空格,正确地放置标点符号。然后是一个空格和第一个我正在模拟的进度条的点。在不必要的情况下,消息还会被输入页码(格式为3,前导为0),以通知用户正在处理进程,这也将反映我们稍后在右边构建的周期的计数。
import sys
page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
# some stuff…
# search, scrub, and build bulk output list[], count items,
# set done flag True
page=page+1 #done flag set in 'some_stuff'
sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
sys.stdout.flush()
if done: #( flag alternative to break, exit or quit)
print('\nSorting', item_count, 'items')
page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
print(list[item_count])
#print footers here
if not (len(list)==items):
print('#error_handler')
The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03'))
line. First, to erase to the left, it backs up the cursor over the three numeric characters with the '\b\b\b' as ⌫⌫⌫ rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write()
waits for a full buffer or the output channel to close, the sys.stdout.flush()
forces the immediate write. sys.stdout.flush()
is built into the end of print()
which is bypassed with print(txt, end='' )
. Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.
进度条肉在sys.t outout .write('\b\b\b \b\b\b)。' +格式(页面,“03”))。首先,抹去左边,它支持光标在三个数字字符“\ b \ b \ b”作为⌫⌫⌫抹掉,滴新时期增加进度条的长度。然后,它会写入到目前为止已经进展到的页面的三位数。因为sys.stdout.write()等待一个完整的缓冲区或输出通道关闭,所以sys.stdout.flush()强制立即写入。flush()是内置到print()的末尾的,这是通过print(txt, end= ")来完成的。然后,代码循环遍历它平常的时间密集型操作,直到它返回这里擦去3位数字,添加一个句点,再写3位数字,递增。
The three digits wiped and rewritten is by no means necessary - it's just a flourish which exemplifies sys.stdout.write()
versus print()
. You could just as easily prime with a period and forget the three fancy backslash-b ⌫ backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through - without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush()
pair.
擦去和重写的3位数字并不是必须的——它只是一个花哨的例子,演示了system .stdout.write()和print()。你可以'一段和忘记这三个花式backslash-b⌫退格(当然不是写作格式的页面数)通过印刷栏再通过一个每次-没有空格或换行只用sys.stdout.write(' . ');sys.stdout.flush()。
Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ⌫ rubout but instead prints a space, creating an apparent list of fractions instead.
请注意,树莓πIDLE3 Python shell并不尊敬退格⌫抹掉,而是输出空间,创建一个明显的分数而不是列表。
—(o=8> wiz
-(o = 8 >奇才
#18
4
python 2.6+:
python 2.6 +:
from __future__ import print_function # needs to be first statement in file
print('.', end='')
python 3:
python 3:
print('.', end='')
python <= 2.5:
python < = 2.5:
import sys
sys.stdout.write('.')
if extra space is OK after each print, in python 2
在python 2中,如果在每次打印之后都可以使用额外的空间
print '.',
misleading in python 2 - avoid:
在python 2中具有误导性-避免:
print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `
#19
4
i recently had the same problem..
我最近也遇到了同样的问题。
i solved it by doing:
我通过做:
import sys, os
# reopen stdout with "newline=None".
# in this mode,
# input: accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep
sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)
for i in range(1,10):
print(i)
this works on both unix and windows ... have not tested it on macosx ...
这适用于unix和windows……还没有在macosx上测试过……
hth
hth
#20
4
You will notice that all the above answers are correct. But I wanted to make a shortcut to always writing the " end='' " parameter in the end.
你会注意到上面所有的答案都是正确的。但是我想做一个捷径,总是在末尾写入“end=”参数。
You could define a function like
你可以像这样定义一个函数
def Print(*args,sep='',end='',file=None,flush=False):
print(*args,sep=sep,end=end,file=file,flush=flush)
It would accept all the number of parameters. Even it will accept all the other parameters like file, flush ,etc and with the same name.
它会接受所有的参数。甚至它将接受所有其他参数,如文件、刷新等,并使用相同的名称。
#21
3
Many of these answers seem a little complicated. In Python 3.X you simply do this,
这些答案中的许多似乎有点复杂。Python 3。你只要这样做,
print(<expr>, <expr>, ..., <expr>, end=" ")
The default value of end is "\n". We are simply changing it to a space or you can also use end="".
end的默认值是“\n”。我们只是将它更改为一个空间,或者也可以使用end=""。
#22
3
for i in xrange(0,10): print '\b.',
This worked in both 2.7.8 & 2.5.2 (Canopy and OSX terminal, respectively) -- no module imports or time travel required.
这在2.7.8和2.5.2(分别是Canopy和OSX终端)中都适用——不需要模块导入或时间旅行。
#23
1
Here's a general way of printing without inserting a newline.
这里有一种不插入换行符的打印方法。
Python 3
Python 3
for i in range(10):
print('.',end = '')
In Python 3 it is very simple to implement
在Python 3中,实现它非常简单
#24
0
...you do not need to import any library. Just use the delete character:
…您不需要导入任何库。只需使用删除字符:
BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),
this removes the newline and the space (^_^)*
这个删除换行符和空间(^ _ ^)*
#25
-4
My understanding is that the comma suppressed the space The 3 dots are relics of the interpreter
我的理解是,逗号压制了空间,这三个点是解释器的遗物
for i in range(0,10): print".\n", ... . . . . . . . . . .
对于范围(0,10)中的i: print。\n“,……”
#1
1835
General way
import sys
sys.stdout.write('.')
You may also need to call
你可能还需要打电话
sys.stdout.flush()
to ensure stdout
is flushed immediately.
确保stdout立即被刷新。
Python 2.6+
From Python 2.6 you can import the print
function from Python 3:
从Python 2.6可以从Python 3导入打印函数:
from __future__ import print_function
This allows you to use the Python 3 solution below.
这允许您使用下面的Python 3解决方案。
Python 3
In Python 3, the print
statement has been changed into a function. In Python 3, you can instead do:
在Python 3中,print语句已被更改为函数。在Python 3中,您可以改为:
print('.', end='')
This also works in Python 2, provided that you've used from __future__ import print_function
.
如果您已经使用了__future__导入print_function,那么它也可以在Python 2中工作。
If you are having trouble with buffering, you can flush the output by adding flush=True
keyword argument:
如果您在缓冲方面有问题,可以通过添加flush=True关键字参数来刷新输出:
print('.', end='', flush=True)
#2
269
It should be as simple as described at this link by Guido Van Rossum:
它应该像圭多·范·罗瑟姆在这个链接中所描述的那样简单:
Re: How does one print without a c/r ?
没有信用证怎么打印?
http://legacy.python.org/search/hypermail/python-1992/0115.html
http://legacy.python.org/search/hypermail/python-1992/0115.html
Is it possible to print something but not automatically have a carriage return appended to it ?
是否可以打印某样东西,但不可以自动将回车附加到它上面?
Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline:
是的,在最后一个参数之后添加一个逗号来打印。例如,这个循环打印数字0。用空格隔开的线。注意添加最后换行的无参数“打印”:
>>> for i in range(10):
... print i,
... else:
... print
...
0 1 2 3 4 5 6 7 8 9
>>>
#3
157
Note: The title of this question used to be something like "How to printf in python?"
注意:这个问题的标题曾经类似于“如何在python中printf ?”
Since people may come here looking for it based on the title, Python also supports printf-style substitution:
由于人们可能会基于标题来寻找它,Python也支持printf样式的替换:
>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
... print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three
And, you can handily multiply string values:
可以方便地将字符串值相乘:
>>> print "." * 10
..........
#4
83
Use the python3-style print function for python2.6+ (will also break any existing keyworded print statements in the same file.)
在python2.6+中使用python3风格的打印函数(也会在同一个文件中破坏任何现有的关键字打印语句)。
# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
print('.', end='')
To not ruin all your python2 print keywords, create a separate printf.py
file
为了不破坏所有的python2打印关键字,创建一个单独的printf。py文件
# printf.py
from __future__ import print_function
def printf(str, *args):
print(str % args, end='')
Then, use it in your file
然后,在你的文件中使用它
from printf import printf
for x in xrange(10):
printf('.')
print 'done'
#..........done
More examples showing printf style
更多显示printf样式的示例
printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000
#5
37
This is not the answer to the question in the title, but it's the answer on how to print on the same line:
这不是标题中问题的答案,但它是关于如何在同一条线上打印的答案:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
#6
20
The new (as of Python 3.0) print
function has an optional end
parameter that lets you modify the ending character. There's also sep
for separator.
新的(从Python 3.0开始)打印函数有一个可选的结束参数,允许您修改结束字符。还有sep用于分隔符。
#7
17
You can just add ,
in the end of print
function so it won't print on new line.
你可以在打印函数的末尾添加,这样它就不会在新行上打印了。
#8
13
Using functools.partial to create a new function called printf
使用functools。偏置以创建一个名为printf的新函数
>>> import functools
>>> printf = functools.partial(print, end="")
>>> printf("Hello world\n")
Hello world
Easy way to wrap a function with default parameters.
用默认参数包装函数的简单方法。
#9
13
print
function in python automatically generates a new line. You could try:
在python中打印函数自动生成一条新行。你可以试试:
print("Hello World", end="")
打印(“Hello World”,最后= " ")
#10
9
Code for Python 3.6.1
Python代码3.6.1
for i in range(0,10): print('.' , end="")
Output
输出
..........
>>>
#11
7
You can do it with end
argument of print. In python3 range() returns iterator and xrange() doesn't exist.
你可以用结束参数打印。在python3 range()中返回迭代器,xrange()不存在。
for i in range(10): print('.', end='')
#12
7
you want to print something in for loop right;but you don't want it print in new line every time.. for example:
你想要在for循环中打印一些东西,但是你不希望每次都在新的行中打印。例如:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print "hi"
但是你想让它像这样打印:嗨,嗨,你好,你好,对吗???? ?在打印“hi”后添加一个逗号
Example:
例子:
for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi
i在range(0,5)中:打印“hi”输出:hi hi hi hi hi hi hi hi hi hi hi hi hi
#13
7
You can try:
你可以尝试:
import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')
#14
6
In Python 3, printing is a function. When you call
在Python 3中,打印是一个函数。当你打电话
print ('hello world')
Python translates it to
Python翻译它
print ('hello world', end = '\n')
You can change end to whatever you want.
你可以改变任何你想要的东西。
print ('hello world', end = '')
print ('hello world', end = ' ')
#15
5
for i in xrange(0,10): print '.',
This will work for you. here comma (,) is important after print. Got help from : http://freecodeszone.blogspot.in/2016/11/how-to-print-in-python-without-newline.html
这对你有用。这里的逗号(,)在打印后很重要。从http://freecodeszone.blogspot.in/2016/11/how to printin -python-without newline.html获得帮助
#16
4
You can do the same in python3 as follows :
你可以在python3中这样做:
#!usr/bin/python
i = 0
while i<10 :
print('.',end='')
i = i+1
and execute it with python filename.py
or python3 filename.py
并使用python文件名执行它。py或python3 filename.py
#17
4
@lenooh satisfied my query. I discovered this article while searching for 'python suppress newline'. I'm using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn't want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn't cruncxed to a halt nor been sent to lunch on a merry infinite loop - as a plea to 'leave me be, I'm doing fine, but this may take some time.' interactive message - like a progress bar in text.
@lenooh满意我的查询。我在搜索“python抑制换行”时发现了这篇文章。我在树莓派上使用IDLE3开发Python 3.2 for PuTTY。我想在PuTTY命令行上创建一个进度条。我不希望页面滚动。我想要一条横线,让用户放心,这个程序并没有陷入停顿,也没有被发送到午餐的欢乐无限循环——作为一种请求,“离开我吧,我做得很好,但这可能需要一些时间。”互动信息——就像文本中的进度条。
The print('Skimming for', search_string, '\b! .001', end='')
initializes the message by preparing for the next screen-write, which will print three backspaces as ⌫⌫⌫ rubout and then a period, wiping off '001' and extending the line of periods. After search_string
parrots user input, the \b!
trims the exclamation point of my search_string
text to back over the space which print()
otherwise forces, properly placing the punctuation. That's followed by a space and the first 'dot' of the 'progress bar' which I'm simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.
打印('Skimming for', search_string, '\b!措施”,结束= ")初始化消息,准备下一个screen-write将打印三退格⌫⌫⌫擦掉,然后一段时间内,抹去了‘001’和扩展的时期。在search_string鹦鹉螺用户输入后,\b!将search_string文本的感叹号调整回print()所强制的空格,正确地放置标点符号。然后是一个空格和第一个我正在模拟的进度条的点。在不必要的情况下,消息还会被输入页码(格式为3,前导为0),以通知用户正在处理进程,这也将反映我们稍后在右边构建的周期的计数。
import sys
page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
# some stuff…
# search, scrub, and build bulk output list[], count items,
# set done flag True
page=page+1 #done flag set in 'some_stuff'
sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
sys.stdout.flush()
if done: #( flag alternative to break, exit or quit)
print('\nSorting', item_count, 'items')
page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
print(list[item_count])
#print footers here
if not (len(list)==items):
print('#error_handler')
The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03'))
line. First, to erase to the left, it backs up the cursor over the three numeric characters with the '\b\b\b' as ⌫⌫⌫ rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write()
waits for a full buffer or the output channel to close, the sys.stdout.flush()
forces the immediate write. sys.stdout.flush()
is built into the end of print()
which is bypassed with print(txt, end='' )
. Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.
进度条肉在sys.t outout .write('\b\b\b \b\b\b)。' +格式(页面,“03”))。首先,抹去左边,它支持光标在三个数字字符“\ b \ b \ b”作为⌫⌫⌫抹掉,滴新时期增加进度条的长度。然后,它会写入到目前为止已经进展到的页面的三位数。因为sys.stdout.write()等待一个完整的缓冲区或输出通道关闭,所以sys.stdout.flush()强制立即写入。flush()是内置到print()的末尾的,这是通过print(txt, end= ")来完成的。然后,代码循环遍历它平常的时间密集型操作,直到它返回这里擦去3位数字,添加一个句点,再写3位数字,递增。
The three digits wiped and rewritten is by no means necessary - it's just a flourish which exemplifies sys.stdout.write()
versus print()
. You could just as easily prime with a period and forget the three fancy backslash-b ⌫ backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through - without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush()
pair.
擦去和重写的3位数字并不是必须的——它只是一个花哨的例子,演示了system .stdout.write()和print()。你可以'一段和忘记这三个花式backslash-b⌫退格(当然不是写作格式的页面数)通过印刷栏再通过一个每次-没有空格或换行只用sys.stdout.write(' . ');sys.stdout.flush()。
Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ⌫ rubout but instead prints a space, creating an apparent list of fractions instead.
请注意,树莓πIDLE3 Python shell并不尊敬退格⌫抹掉,而是输出空间,创建一个明显的分数而不是列表。
—(o=8> wiz
-(o = 8 >奇才
#18
4
python 2.6+:
python 2.6 +:
from __future__ import print_function # needs to be first statement in file
print('.', end='')
python 3:
python 3:
print('.', end='')
python <= 2.5:
python < = 2.5:
import sys
sys.stdout.write('.')
if extra space is OK after each print, in python 2
在python 2中,如果在每次打印之后都可以使用额外的空间
print '.',
misleading in python 2 - avoid:
在python 2中具有误导性-避免:
print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `
#19
4
i recently had the same problem..
我最近也遇到了同样的问题。
i solved it by doing:
我通过做:
import sys, os
# reopen stdout with "newline=None".
# in this mode,
# input: accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep
sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)
for i in range(1,10):
print(i)
this works on both unix and windows ... have not tested it on macosx ...
这适用于unix和windows……还没有在macosx上测试过……
hth
hth
#20
4
You will notice that all the above answers are correct. But I wanted to make a shortcut to always writing the " end='' " parameter in the end.
你会注意到上面所有的答案都是正确的。但是我想做一个捷径,总是在末尾写入“end=”参数。
You could define a function like
你可以像这样定义一个函数
def Print(*args,sep='',end='',file=None,flush=False):
print(*args,sep=sep,end=end,file=file,flush=flush)
It would accept all the number of parameters. Even it will accept all the other parameters like file, flush ,etc and with the same name.
它会接受所有的参数。甚至它将接受所有其他参数,如文件、刷新等,并使用相同的名称。
#21
3
Many of these answers seem a little complicated. In Python 3.X you simply do this,
这些答案中的许多似乎有点复杂。Python 3。你只要这样做,
print(<expr>, <expr>, ..., <expr>, end=" ")
The default value of end is "\n". We are simply changing it to a space or you can also use end="".
end的默认值是“\n”。我们只是将它更改为一个空间,或者也可以使用end=""。
#22
3
for i in xrange(0,10): print '\b.',
This worked in both 2.7.8 & 2.5.2 (Canopy and OSX terminal, respectively) -- no module imports or time travel required.
这在2.7.8和2.5.2(分别是Canopy和OSX终端)中都适用——不需要模块导入或时间旅行。
#23
1
Here's a general way of printing without inserting a newline.
这里有一种不插入换行符的打印方法。
Python 3
Python 3
for i in range(10):
print('.',end = '')
In Python 3 it is very simple to implement
在Python 3中,实现它非常简单
#24
0
...you do not need to import any library. Just use the delete character:
…您不需要导入任何库。只需使用删除字符:
BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),
this removes the newline and the space (^_^)*
这个删除换行符和空间(^ _ ^)*
#25
-4
My understanding is that the comma suppressed the space The 3 dots are relics of the interpreter
我的理解是,逗号压制了空间,这三个点是解释器的遗物
for i in range(0,10): print".\n", ... . . . . . . . . . .
对于范围(0,10)中的i: print。\n“,……”