插入项目到列表在Python,而不是覆盖
问题描述:
我需要的字“和”添加到我的列表的末尾,如插入项目到列表在Python,而不是覆盖
A,B和C
到目前为止我得到的逗号整理出来。我已经看到了如何在最后一个项目在列表中拿到这里
Getting the last element of a list in Python
,但不希望覆盖或替换的最后一个项目,只需添加在它前面的一个词。这是我到目前为止有:
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)
print('The list is: ' + ", ".join(listToPrint), end="")
仿佛它不是太明显,我是相当新的蟒蛇,这是在PyCharm正在编制。
谢谢进阶
答
使用负切片为您的列表如下:
', '.join(listToPrint[:-1]) + ', and ' + listToPrint[-1]
随着format()
功能:
'{}, and {}'.format(', '.join(listToPrint[:-1]), listToPrint[-1])
format()
与', '.join(listToPrint[:-1])
和值将替换第{}
第二个{}
的值为listToPrint[-1]
。有关详细信息,请点击这里它的文档format()
输出:
Enter a word to add to the list (press return to stop adding words) > 'Hello'
Enter a word to add to the list (press return to stop adding words) > 'SOF'
Enter a word to add to the list (press return to stop adding words) > 'Users'
# ...
>>> print('{}, and {}'.format(', '.join(listToPrint[:-1]), listToPrint[-1]))
Hello, SOF, and Users
+0
这是完美的!我新的我需要负面切片,只是不知道如何格式化。因此,无论列表大小如何,我都可以根据需要对其进行格式化。这个代码是如何工作的: '{}和{}' – enjoyitwhileucan
最简单的破坏性的方式是改变最后一项'和X',例如'printToPrint [-1] ='和'+ listToPrint [-1]'就在'print()'之前。 – AChampion