Python:for循环 - 在同一行打印 [英] Python: for loop - print on the same line
问题描述
我有一个关于在 Python 3 中使用 for
循环在同一行上打印的问题.我搜索了答案,但找不到任何相关内容.
I have a question about printing on the same line using for
loop in Python 3. I searched for the answer but I couldn't find any relevant.
所以,我有这样的事情:
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: ')
当用户输入A short sentence"时,函数应该对它做一些事情,并且应该打印在同一行上.假设函数在每个单词的末尾添加 't',所以输出应该是
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
At shortt sentencet
但是,目前输出是:
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
它被迭代,最后我打印 new_string
?
and it is iterated and at the end I print new_string
?
推荐答案
在print
函数中使用end
参数
print(new_item, end=" ")
还有另一种方法可以做到这一点,使用理解和join
.
There is another way to do this, using comprehension and join
.
print (" ".join([function(word) for word in split]))
这篇关于Python:for循环 - 在同一行打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!