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()
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.
CodePudding user response:
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.
CodePudding user response:
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)