添加和删除后,最后一个列表项出现在新列表中

2024-09-28 17:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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])

Tags: andto代码true列表forinput方式
2条回答

下面的代码实现了您想要的功能。你知道吗

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)
listToPrint[-1] = "and " + listToPrint[-1]

print(listToPrint)

您只需str.join()将您的单词的一部分(无最后一个)打印成一行:

print("{}, and {}".format(", ".join(listToPrint[:-1]), listToPrint[-1]))

相关问题 更多 >