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

具体来说,假设我有:

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

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

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


当前回答

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

我简单地使用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
import time

startnumber = 1
endnumber = 100

# solution A without a for loop
start_time = time.clock()
m = map(str, range(startnumber, endnumber + 1))
print(' '.join(m))
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('took {0}ms\n'.format(timetaken))

# solution B: with a for loop
start_time = time.clock()
for i in range(startnumber, endnumber + 1):
    print(i, end=' ')
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('\ntook {0}ms\n'.format(timetaken))
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 100
took 21.1986929975ms

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 100 
took 491.466823551ms

或者更简单:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

End ="\r"将覆盖第一次打印的开头[0:]。

如果您希望它作为字符串,您可以使用

number_string = ""
for i in range(1, 100):
  number_string += str(i)
print(number_string)

在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

实现这一点的最佳方法是使用\r字符

试试下面的代码:

import time
for n in range(500):
  print(n, end='\r')
  time.sleep(0.01)
print()  # start new line so most recently printed number stays