我想做几个语句,给出标准输出,而不看到换行之间的语句。

具体来说,假设我有:

for item in range(1,100):
    print item

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?


当前回答

打印语句末尾的逗号省略了新行。

for i in xrange(1,100):
  print i,

但这不会覆盖。

其他回答

注意:我之所以指出这个解决方案,是因为如果下一次打印的长度小于前一次打印的长度,我所见过的大多数其他解决方案都不起作用。

如果您知道要删除什么,并且可以使用全局变量,那么只需用空格覆盖最后一行。

在打印之前,将字符串的长度存储为' n '。 打印它,但以' \r '结尾(它返回行首)。 下次,在打印信息之前,在该行上打印“n”个空格。

_last_print_len = 0
def reprint(msg, finish=False):
    global _last_print_len
    
    # Ovewrites line with spaces.
    print(' '*_last_print_len, end='\r')
    
    if finish:
        end = '\n'
        # If we're finishing the line, we won't need to overwrite it in the next print.
        _last_print_len = 0
    else:
        end = '\r'
        # Store len for the next print.
        _last_print_len = len(msg)
    
    # Printing message.
    print(msg, end=end)

例子:

for i in range(10):
    reprint('Loading.')
    time.sleep(1)
    reprint('Loading..')
    time.sleep(1)
    reprint('Loading...')
    time.sleep(1)

for i in range(10):
    reprint('Loading.')
    time.sleep(1)
    reprint('Loading..')
    time.sleep(1)
    reprint('Loading...', finish=True)
    time.sleep(1)

打印语句末尾的逗号省略了新行。

for i in xrange(1,100):
  print i,

但这不会覆盖。

和其他例子一样, 我使用类似的方法,但不是花时间计算最后的输出长度,等等,

我简单地使用ANSI代码转义移回行开始,然后在打印当前状态输出之前清除整行。

import sys

class Printer():
    """Print things to stdout on one line dynamically"""
    def __init__(self,data):
        sys.stdout.write("\r\x1b[K"+data.__str__())
        sys.stdout.flush()

为了在你的迭代循环中使用,你只需要调用如下代码:

x = 1
for f in fileList:
    ProcessFile(f)
    output = "File number %d completed." % x
    Printer(output)
    x += 1   

点击这里查看更多信息

在Python 3中,你可以这样做:

for item in range(1,10):
    print(item, end =" ")

输出:

1 2 3 4 5 6 7 8 9 

Tuple:你可以对Tuple做同样的事情:

tup = (1,2,3,4,5)

for n in tup:
    print(n, end = " - ")

输出:

1 - 2 - 3 - 4 - 5 - 

另一个例子:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for item in list_of_tuples:
    print(item)

输出:

(1, 2)
('A', 'B')
(3, 4)
('Cat', 'Dog')

你甚至可以像这样解包你的元组:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]

# Tuple unpacking so that you can deal with elements inside of the tuple individually
for (item1, item2) in list_of_tuples:
    print(item1, item2)   

输出:

1 2
A B
3 4
Cat Dog

另一个变化:

list_of_tuples = [(1,2),('A','B'), (3,4), ('Cat', 'Dog')]
for (item1, item2) in list_of_tuples:
    print(item1)
    print(item2)
    print('\n')

输出:

1
2


A
B


3
4


Cat
Dog
for item in range(1,100):
    if item==99:
        print(item,end='')
    else:
        print (item,end=',')

输出: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12、13、14、15、16、17、18、19日,20日,21日,22日,23日,24日,25日,26日,27日,28日,29、30、31、32、33、34、35、36、37、38、39、40、41、42、43、44、45、46岁,47岁,48岁,49岁,50岁,51岁,52岁,53岁,54岁,55岁,56岁,57岁,今年58岁,59岁,60岁,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99