Python:for循环 - 在同一行上打印

Som*_*One 9 python string python-3.x

我有一个关于for在Python 3中使用循环在同一行上打印的问题.我搜索了答案,但我找不到任何相关的.

所以,我有这样的事情:

def function(variable):

    some code here

    return result


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: ')
Run Code Online (Sandbox Code Playgroud)

当用户输入句子"短句"时,该函数应该对它做一些事情并且它应该打印在同一行上.假设函数将't'添加到每个单词的末尾,因此输出应为

在短期内判刑

但是,目前的输出是:


短期内
判刑

如何轻松地在同一行上打印结果?或者我应该制作一个新的字符串

new_string = ''
new_string = new_string + new_item
Run Code Online (Sandbox Code Playgroud)

它是迭代的,最后我打印new_string?

the*_*eye 18

endprint函数中使用参数

print(new_item, end=" ")
Run Code Online (Sandbox Code Playgroud)

还有另一种方法可以做到这一点,使用理解和join.

print (" ".join([function(word) for word in split]))
Run Code Online (Sandbox Code Playgroud)


小智 8

最简单的解决方案是在print语句中使用逗号:

for i in range(5):
    print i,

#prints 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

请注意,没有尾随换行符; print循环之后没有参数会添加它.