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

具体来说,假设我有:

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

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

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


当前回答

将打印项更改为:

在Python 2.7中,打印项 print(item, end=" "

如果你想动态打印数据,请使用以下语法:

打印(item, sep=' ', end= ", flush=True

其他回答

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

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

使用print item,使print语句省略换行符。

在python3中,它是print(item, end=" ")。

如果你想让每个数字都显示在相同的位置,使用例如(Python 2.7):

to = 20
digits = len(str(to - 1))
delete = "\b" * (digits + 1)
for i in range(to):
    print "{0}{1:{2}}".format(delete, i, digits),

在Python 3中,这有点复杂;这里你需要刷新系统。Stdout或者在循环结束之前它不会打印任何东西:

import sys
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits)
for i in range(to):
   print("{0}{1:{2}}".format(delete, i, digits), end="")
   sys.stdout.flush()

实现这一点的最佳方法是使用\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
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