我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
for item in range(1,100):
print item
结果是:
1
2
3
4
.
.
.
如何让它看起来像:
1 2 3 4 5 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
for item in range(1,100):
print item
结果是:
1
2
3
4
.
.
.
如何让它看起来像:
1 2 3 4 5 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
当前回答
你可以在你的print语句中添加一个尾随逗号,在每次迭代中打印一个空格而不是换行符:
print item,
或者,如果你使用的是Python 2.6或更高版本,你可以使用新的print函数,它允许你指定甚至不应该在打印的每一项的结尾出现空格(或者允许你指定任何你想要的结尾):
from __future__ import print_function
...
print(item, end="")
最后,你可以通过从sys模块导入标准输出直接写入标准输出,它会返回一个类文件对象:
from sys import stdout
...
stdout.write( str(item) )
其他回答
或者更简单:
import time
a = 0
while True:
print (a, end="\r")
a += 1
time.sleep(0.1)
End ="\r"将覆盖第一次打印的开头[0:]。
在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
你可以在你的print语句中添加一个尾随逗号,在每次迭代中打印一个空格而不是换行符:
print item,
或者,如果你使用的是Python 2.6或更高版本,你可以使用新的print函数,它允许你指定甚至不应该在打印的每一项的结尾出现空格(或者允许你指定任何你想要的结尾):
from __future__ import print_function
...
print(item, end="")
最后,你可以通过从sys模块导入标准输出直接写入标准输出,它会返回一个类文件对象:
from sys import stdout
...
stdout.write( str(item) )
我认为一个简单的连接应该工作:
nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)
对于那些像我一样挣扎的人,我提出了以下似乎在python 3.7.4和3.5.2中都可以工作的方法。
I expanded the range from 100 to 1,000,000 because it runs very fast and you may not see the output. This is because one side effect of setting end='\r' is that the final loop iteration clears all of the output. A longer number was needed to demonstrate that it works. This result may not be desirable in all cases, but was fine in mine, and OP didn't specify one way or another. You could potentially circumvent this with an if statement that evaluates the length of the array being iterated over, etc. The key to get it working in my case was to couple the brackets "{}" with .format(). Otherwise, it didn't work.
以下应按原样工作:
#!/usr/bin/env python3
for item in range(1,1000000):
print("{}".format(item), end='\r', flush=True)