Print new output on same line

I want to print the looped output to the screen on the same line.

How do I this in the simplest way for Python 3.x

I know this question has been asked for Python 2.7 by using a comma at the end of the line i.e. print I, but I can't find a solution for Python 3.x.

i = 0
while i <10:
i += 1
## print (i) # python 2.7 would be print i,
print (i) # python 2.7 would be 'print i,'

Screen output.

1
2
3
4
5
6
7
8
9
10

What I want to print is:

12345678910

New readers visit this link aswell http://docs.python.org/release/3.0.1/whatsnew/3.0.html

424870 次浏览

来自 help(print):

Help on built-in function print in module builtins:


print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)


Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

可以使用 end关键字:

>>> for i in range(1, 11):
...     print(i, end='')
...
12345678910>>>

请注意,您必须自己将最后一行换行符 print()。顺便说一句,在 Python2中不会得到带有逗号的“12345678910”,而是得到 1 2 3 4 5 6 7 8 9 10

你可以这样做:

>>> print(''.join(map(str,range(1,11))))
12345678910
>>> for i in range(1, 11):
...     print(i, end=' ')
...     if i==len(range(1, 11)): print()
...
1 2 3 4 5 6 7 8 9 10
>>>

这是如何做到这一点,使打印不运行后面的提示在下一行。

* for python 2. x *

使用后面的逗号以避免换行。

print "Hey Guys!",
print "This is how we print on the same line."

上述代码片段的输出将是,

Hey Guys! This is how we print on the same line.

* for python 3. x *

for i in range(10):
print(i, end="<separator>") # <separator> = \n, <space> etc.

上述代码片段的输出将是(当 <separator> = " "时) ,

0 1 2 3 4 5 6 7 8 9

让我们举一个例子,您想要在同一行中打印从0到 n 的数字。您可以在以下代码的帮助下完成此操作。

n=int(raw_input())
i=0
while(i<n):
print i,
i = i+1

在输入端,n = 5

Output : 0 1 2 3 4

与上述建议类似,你可以这样做:

print(i, end=',')

Output: 0,1,2,3,

print("single",end=" ")
print("line")

这会产生输出

single line

用来回答问题

i = 0
while i <10:
i += 1
print (i,end="")