Domo
Domo

Reputation: 5

How to split a list to add delimiters

I want to add commas as separators except for the last pair of words using python. I believe I should split the list but not sure where to start.

def main():

word = input('Enter next word or quit: ')
store_words = [word]
while word != 'quit':
    if word == 'quit':
        break
    word = input('Enter next word or quit: ')
    store_words.append(word)
    
store_words.remove('quit')
print(*store_words, sep=',')

main()

enter image description here

I've tried splitting the list, but it states that the list has no attribute split. I did more researching and some suggested to open a file and use readline.

Upvotes: 0

Views: 43

Answers (2)

ramzeek
ramzeek

Reputation: 2315

For the main part of your question, try using a join command:

print(', '.join(store_words[:-1]) + " and " + store_words[-1])

Also note, that you can write your loop in fewer lines. Having if word == 'quit': break as the first line inside your while word != 'quit': loop doesn't do anything because it will only be called when word != 'quit' is True. Instead, consider something like this:

word = input('Enter next word or quit: ')
store_words = [word]
while word != 'quit':
    word = input('Enter next word or quit: ')
    if word != 'quit':
        store_words.append(word)

Upvotes: 1

OTheDev
OTheDev

Reputation: 2967

After you remove 'quit' from the list, add and/or modify the following lines as you see fit.

my_string = ','.join(store_words)
index = my_string.rfind(',')
my_string = my_string[0:index] + " and " + my_string[index + 1:]
print(my_string)

Example session:

Enter next word or quit: green
Enter next word or quit: eggs
Enter next word or quit: ham
Enter next word or quit: quit
green,eggs and ham

I hope this helps. Please let me know if there are any questions.

Upvotes: 1

Related Questions