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

Python 添加和删除后,最后一个列表项出现在新列表中,python,list,python-3.x,Python,List,Python 3.x,我正在学习Python,但在这段代码中遇到了问题。我正在使用for循环在列表中循环,我需要它在最后一项之前打印单词”和“”。我让它工作,但不是我想要的方式 当我打印时,列表中不会出现和“+最后一项”,而会出现在列表之外。有人能告诉我我做错了什么吗 listToPrint = [] while True: newWord = input("Enter a word to add to the list (press return to stop adding words) > ")

我正在学习Python,但在这段代码中遇到了问题。我正在使用for循环在列表中循环,我需要它在最后一项之前打印单词
”和“
”。我让它工作,但不是我想要的方式

当我打印时,列表中不会出现
和“+最后一项”
,而会出现在列表之外。有人能告诉我我做错了什么吗

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()
一个单词片段,不包含最后一个单词,然后打印行中的最后一个单词:

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

您只需
str.join()
一个单词片段,不包含最后一个单词,然后打印行中的最后一个单词:

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

下面的代码做了您似乎想要的事情

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)

下面的代码做了您似乎想要的事情

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)

列表的切片返回一个列表
listToPrint[0:-1]
是一个列表,所以如果你是这个意思的话,右括号出现在
前面。我以为是这样的,但我不知道如何处理这个问题。列表的切片返回一个列表
listToPrint[0:-1]
是一个列表,所以如果这是你的意思的话,前面会出现一个右大括号。我原以为是这样的,但我不知道如何处理这个问题。我对print({},and{}.format(“,”.join(listToPrint[:-1]),listToPrint[-1])做了一个小小的更改,但这就是我要找的。你能解释一下这段代码或者告诉我在哪里可以知道这是什么吗?@KennyFreeman-你也可以使用你的原始语句:
print(“,”。join(listToPrint[:-1])、end=“、and”+listToPrint[-1]+“\n”)
,但是(意见时间)只要有可能,最好控制输出格式,我发现它更可读。我喜欢你最初的方式。我只是不知道你可以像用字符串一样格式化。这叫什么?@KennyFreeman-是Python中进行复杂字符串格式化的原生方法和首选方法。您可以在网站上阅读更多关于它的使用的信息,我对print(“{}和{}.format(“,”.join(listToPrint[:-1])、listToPrint[-1])做了一个小的更改,但这就是我要找的。你能解释一下这段代码或者告诉我在哪里可以知道这是什么吗?@KennyFreeman-你也可以使用你的原始语句:
print(“,”。join(listToPrint[:-1])、end=“、and”+listToPrint[-1]+“\n”)
,但是(意见时间)只要有可能,最好控制输出格式,我发现它更可读。我喜欢你最初的方式。我只是不知道你可以像用字符串一样格式化。这叫什么?@KennyFreeman-是Python中进行复杂字符串格式化的原生方法和首选方法。你可以在网站上阅读更多关于它使用的信息