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

10
我是一名有用的助手,可以为您翻译文本。以下是您需要翻译的内容:

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

所以,我有这样的东西:

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”,则输出应为:
At shortt sentencet

然而,目前的输出结果是:
At
shortt
sentencet

我该如何轻松地在同一行上打印结果?还是我应该创建一个新的字符串?
new_string = ''
new_string = new_string + new_item

然后进行迭代,并在最后打印new_string吗?

3个回答

25

使用print函数中的end参数

print(new_item, end=" ")

使用列表推导式和join方法也可以实现这个目的。

print (" ".join([function(word) for word in split]))

8
最简单的解决方案是在您的print语句中使用逗号:
>>> for i in range(5):
...   print i,
...
0 1 2 3 4

请注意,这里没有尾随的换行符;在循环之后没有带参数的print会添加它。

请注意,这仅适用于Python 2,并且OP似乎正在使用Python 3。 - wjandrea

2

由于在Python3中,print是一个函数,因此您可以将您的代码简化为:

while item:
    split = item.split()
    print(*map(function, split), sep=' ')
    item = input('Enter a sentence: ')

演示:

$ python3 so.py
Enter a sentence: a foo bar
at foot bart

更好的方法是使用 iterpartial
from functools import partial
f = partial(input, 'Enter a sentence: ')

for item in iter(f, ''):
    split = item.split()
    print(*map(function, split), sep=' ')

演示:

$ python3 so.py
Enter a sentence: a foo bar
at foot bart
Enter a sentence: a b c
at bt ct
Enter a sentence: 
$

1
我一直有这个疑问,我们能否使用 iter 来在遇到列表中的任何项时停止? - thefourtheye
1
@thefourtheye 我不这么认为,因为我们无法在iter内部访问item,但是我们可以使用itertools.takewhile来实现。 - Ashwini Chaudhary
@hcwhsa 你的意思是我们可以结合使用 itertakewhile 来实现这个功能吗? - thefourtheye
1
请问给我点踩的人,能否解释一下原因? - thefourtheye
1
@thefourtheye 不是,只需要使用takewhilefor x in takewhile(lambda x: x not in my_list, (x() for x in repeat(f))),其中 ff = partial(input, '输入一个句子:') - Ashwini Chaudhary

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接