Python:for循环 - 在同一行打印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20031734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: for loop - print on the same line
提问by SomeOne
I have a question about printing on the same line using forloop in Python 3. I searched for the answer but I couldn't find any relevant.
我有一个关于for在 Python 3 中使用循环在同一行上打印的问题。我搜索了答案,但找不到任何相关内容。
So, I have something like this:
所以,我有这样的事情:
def function(s):
return s + 't'
item = input('Enter a sentence: ')
while item != '':
split = item.split()
for word in split:
new_item = function(word)
print(new_item)
item = input('Enter a sentence: ')
When a user types in 'A short sentence', the function should do something with it and it should be printed on the same line. Let's say that function adds 't' to the end of each word, so the output should be
当用户输入“A short sentence”时,该函数应该对其进行处理,并将其打印在同一行上。假设函数在每个单词的末尾添加 't',所以输出应该是
At shortt sentencet
However, at the moment the output is:
但是,目前的输出是:
At
shortt
sentencet
How can I print the result on the same line easily? Or should I make a new string so
如何轻松地在同一行上打印结果?或者我应该做一个新的字符串
new_string = ''
new_string = new_string + new_item
and it is iterated and at the end I print new_string?
它被迭代,最后我打印new_string?
采纳答案by thefourtheye
Use endparameter in the printfunction
end在print函数中使用参数
print(new_item, end=" ")
There is another way to do this, using comprehension and join.
还有另一种方法可以做到这一点,使用理解和join。
print (" ".join([function(word) for word in split]))
回答by Ashwini Chaudhary
As printis a function in Python3, you can reduce your code to:
作为printPython3 中的函数,您可以将代码简化为:
while item:
split = item.split()
print(*map(function, split), sep=' ')
item = input('Enter a sentence: ')
Demo:
演示:
$ python3 so.py
Enter a sentence: a foo bar
at foot bart
Even better using iterand partial:
from functools import partial
f = partial(input, 'Enter a sentence: ')
for item in iter(f, ''):
split = item.split()
print(*map(function, split), sep=' ')
Demo:
演示:
$ python3 so.py
Enter a sentence: a foo bar
at foot bart
Enter a sentence: a b c
at bt ct
Enter a sentence:
$
回答by Mohsin Khazi
The simplest solution is using a comma in your printstatement:
最简单的解决方案是在print语句中使用逗号:
>>> for i in range(5):
... print i,
...
0 1 2 3 4
Note that there's no trailing newline; printwithout arguments after the loop would add it.
请注意,没有尾随换行符;print循环后没有参数会添加它。

