Please Help Me With This Python List


#1

Hello Everyone!

I'm reaching out to you all for help with this list project I'm working on. What I need to do is create a program that asks for the user to enter a word, and continue to ask until the user hits enter without typing anything. Once the user hits enter without typing anything, I need to create a list of all the words entered. The code I've pasted below does that currently, however, I need to figure out how to add "and" before the last option. I also need to figure out how to add "and" only if we already have more than one word entered.

Here is the code:

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('Your items are:')    #print items in list here
for newWord in listToPrint:
    print(newWord, end=' ')

Would I need to use an if statement loop to create the second portion to add the "and" segment?
Please help! Thank you!


#2

First, we could check the length of the list, and if it is longer than 1, we can insert and in the second last element.

if len(listToPrint) > 1:
    listToPrint.insert(-1,'and')

#3

Ahh... Thank you @mtf. I was able to update the code but now it just looks like I need to figure out how to remove the last , after the and before the last element.

I think I just figured it out actually....

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('Your items are:')    #print items in list here
if len(listToPrint) > 1:
    listToPrint[-1] = ('and ' + listToPrint[-1])
for i in range(len(listToPrint)-1):
    print(listToPrint[i], end=', ')
print('' +str(listToPrint[-1]), end='.')

#4

Generate the string, insert the and, replace ", and," with " and".

print ", ".join(listToPrint).replace(", and,", " and")

Eg.

>>> lst = ['1','2','3','4','6']
>>> lst.insert(-1, '5')
>>> lst.insert(-1, 'and')
>>> lst
['1', '2', '3', '4', '5', 'and', '6']
>>> print (", ".join(lst).replace(", and,", " and"))
1, 2, 3, 4, 5 and 6
>>>