onx*_*nxx 94 python printing python-3.x
我想将循环输出打印到同一行的屏幕上.
我如何以最简单的方式处理Python 3.x.
我知道这个问题已经被要求用于Python 2.7,在行的末尾使用逗号即打印I,但我找不到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,'
Run Code Online (Sandbox Code Playgroud)
屏幕输出.
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
我想要打印的是:
12345678910
Run Code Online (Sandbox Code Playgroud)
新读者访问此链接以及http://docs.python.org/release/3.0.1/whatsnew/3.0.html
DSM*_*DSM 163
来自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.
Run Code Online (Sandbox Code Playgroud)
您可以使用end关键字:
>>> for i in range(1, 11):
... print(i, end='')
...
12345678910>>>
Run Code Online (Sandbox Code Playgroud)
请注意,您必须自己完成print()最终换行.顺便说一句,你不会在Python 2中使用尾随逗号得到"12345678910",你会得到它1 2 3 4 5 6 7 8 9 10.
Sou*_*ami 30
*for python 2.x*
使用尾随逗号来避免换行.
print "Hey Guys!",
print "This is how we print on the same line."
Run Code Online (Sandbox Code Playgroud)
上面代码片段的输出是,
Hey Guys! This is how we print on the same line.
Run Code Online (Sandbox Code Playgroud)
*for python 3.x*
for i in range(10):
print(i, end="<separator>") # <separator> = \n, <space> etc.
Run Code Online (Sandbox Code Playgroud)
上面代码片段的输出是(当<separator> = " "),
0 1 2 3 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)
小智 8
与建议类似,你可以这样做:
print(i,end=',')
Run Code Online (Sandbox Code Playgroud)
输出:0,1,2,3,
小智 7
print("single",end=" ")
print("line")
Run Code Online (Sandbox Code Playgroud)
这将给出输出
single line
Run Code Online (Sandbox Code Playgroud)
对于提出的问题,使用
i = 0
while i <10:
i += 1
print (i,end="")
Run Code Online (Sandbox Code Playgroud)
您可以执行以下操作:
>>> print(''.join(map(str,range(1,11))))
12345678910
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
315570 次 |
| 最近记录: |