2016-12-04 4 views
0

を上書きしないで、私は言葉を追加する必要がある「と」私のリストの最後に、は私がきたこれまでのところ、Pythonでリストに項目を挿入するが、

、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="") 

そのあまりにも明白ではないかのように、私のpythonにかなり新たなんだ、これはPyCharmでコンパイルされています。 format()機能付き

', '.join(listToPrint[:-1]) + ', and ' + listToPrint[-1] 

:このようなあなたのリストについては、ADV

+0

は、最も簡単な破壊的な方法は、例えば、最後の項目に 'とX 'を変更することですあなたの 'print()'の直前で 'listToPrint [-1] = 'と' + listToPrint [-1]'を実行してください。 – AChampion

答えて

1

使用負のスライスで

おかげ

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

format()', '.join(listToPrint[:-1])との値を持つ最初の{}を置き換えます2番目の{}の値はです0。詳細については、こちらのドキュメントを確認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

関連する問題