我有一个关于在Python 3中使用for
循环在同一行上打印的问题。我搜索了答案,但我找不到任何相关内容。
所以,我有这样的事情:
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: ')
当用户输入句子“短句”时,该函数应该对其执行某些操作,并且应该在同一行上打印。 假设函数将't'添加到每个单词的末尾,因此输出应为
简短判决
但是,目前的输出是:
目前
肖特
sentencet
如何轻松地在同一行打印结果?或者我应该创建一个新字符串
new_string = ''
new_string = new_string + new_item
它是迭代的,最后我打印new_string?
答案 0 :(得分:18)
在end
功能
print
参数
print(new_item, end=" ")
使用理解和join
还有另一种方法可以做到这一点。
print (" ".join([function(word) for word in split]))
答案 1 :(得分:8)
最简单的解决方案是在print
语句中使用逗号:
for i in range(5):
print i,
#prints 1 2 3 4 5
请注意,没有尾随换行符;在循环之后没有参数的print
会添加它。
答案 2 :(得分:2)
由于print
是Python3中的一个函数,因此您可以将代码缩减为:
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
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:
$