我想将循环输出打印到同一行的屏幕上。
我如何以最简单的方式使用Python 3.x
我知道这个问题已经被要求用于Python 2.7,在行的末尾使用逗号,即print 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,'
屏幕输出。
1
2
3
4
5
6
7
8
9
10
我想要打印的是:
12345678910
新读者也可以访问此链接http://docs.python.org/release/3.0.1/whatsnew/3.0.html
答案 0 :(得分:152)
来自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()
最终换行符。顺便说一句,你不会在Python 2中使用尾随逗号获得“12345678910”,而是获得1 2 3 4 5 6 7 8 9 10
。
答案 1 :(得分:27)
* 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
答案 2 :(得分:8)
类似于已建议的内容,您可以这样做:
print(i,end=',')
输出:0,1,2,3,
答案 3 :(得分:4)
您可以执行以下操作:
>>> print(''.join(map(str,range(1,11))))
12345678910
答案 4 :(得分:4)
#StandardSQL
WITH landingpages AS (
SELECT
fullVisitorId,
visitID,
h.page.pagePath AS LandingPage
FROM
`project_id.dataset.table`, UNNEST(hits) AS h
WHERE hitNumber = 1
),
sales AS (
SELECT
fullVisitorId, visitID, SUM(totals.transactions) AS Transactions , (SUM(totals.transactionRevenue)/1000000) AS Revenue
FROM
`project_id.dataset.table`
WHERE
totals.visits > 0
AND totals.transactions >= 1
AND totals.transactionRevenue IS NOT NULL
GROUP BY fullVisitorId, visitID
)
SELECT
LandingPage,
SUM(Transactions) AS Transactions,
SUM(Revenue) AS Revenue
FROM landingpages
JOIN sales
ON landingpages.VisitID = sales.VisitID
AND landingpages.fullVisitorId = sales.fullVisitorId
GROUP BY LandingPage
这将给出输出
print("single",end=" ")
print("line")
对于问题使用
single line
答案 5 :(得分:2)
>>> 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
>>>
这是如何做到这一点,以便打印不会在下一行的提示后面运行。
答案 6 :(得分:2)
让我们举例说明你想在同一行打印0到n的数字。您可以借助以下代码执行此操作。
n=int(raw_input())
i=0
while(i<n):
print i,
i = i+1
在输入时,n = 5
Output : 0 1 2 3 4