我正在学习Python,并且对这段代码有问题。我使用for循环遍历列表,需要它在最后一项之前打印单词'and'
。我有它的工作,但不是我想要的方式。你知道吗
当我打印时,'and ' + last item
不是出现在列表内部,而是出现在列表外部。有人能告诉我我做错了什么吗?你知道吗
listToPrint = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
if newWord == "":
break
else:
listToPrint.append(newWord)
for i in range(1):
print(listToPrint[0:-1], end =', ' + 'and ' + listToPrint[-1])
下面的代码实现了您想要的功能。你知道吗
您只需
str.join()
将您的单词的一部分(无最后一个)打印成一行:相关问题 更多 >
编程相关推荐