私は「Pythonで退屈なものを自動化する」を進めています。以下のプログラムから最終的な出力コンマを削除する方法がわかりません。目標は、ユーザーに値の入力を促し続けることです。値はリストに出力され、最後に「and」が挿入されます。出力は次のようになります。
apples, bananas, tofu, and cats
鉱山は次のようになります。
apples, bananas, tofu, and cats,
その最後のカンマが私をNUTSに駆り立てています。
def lister():
listed = []
while True:
print('type what you want to be listed or type nothing to exit')
inputted = input()
if inputted == '':
break
else:
listed.append(inputted+',')
listed.insert(-1, 'and')
for i in listed:
print(i, end=' ')
lister()
書式設定を印刷時間に据え置くことで、リスト内の各文字列にカンマを追加することを回避できます。最後のonを除くすべての項目を結合し、', '
フォーマットを使用して、最後の項目が結合された結合文字列を挿入しますand
。
listed.append(inputed)
...
print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1]))
デモ:
>>> listed = ['a', 'b', 'c', 'd']
>>> print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1]))
a, b, c, and d
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加