Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining words together with a comma, and "and"

Tags:

I'm working through 'Automate the Boring Stuff with Python'. I can't figure out how to remove the final output comma from the program below. The goal is to keep prompting the user to input values, which are then printed out in a list, with "and" inserted before the end. The output should look something like this:

apples, bananas, tofu, and cats 

Mine looks like this:

apples, bananas, tofu, and cats, 

That last comma is driving me 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() 
like image 927
Admin_Who Avatar asked Jun 15 '17 18:06

Admin_Who


People also ask

Can comma and and be used together?

Do You Put a Comma After "And"? If you use a comma with "and," it should always precede the word "and." You should never put a comma after the word "and." This rule applies to both independent clauses joined by "and" and lists of three or more items, as well as any other time "and" might appear in a sentence.

Where do you put comma after and?

If, for example, the word 'and' precedes a clause beginning 'although', you usually put a comma after it and, if it precedes a conditional clause, you normally insert a comma as well.

Do you use Oxford comma With &?

Well, appropriately enough, the Oxford Dictionary has the answer. The proper definition of the Oxford comma is “a comma used after the penultimate item in a list of three or more items, before 'and' or 'or'.” For example: “Today I went to lunch with my roommates, Tom, and Molly.”

What is it called when you join two sentences with a comma?

Grammarly. When you join two independent clauses with a comma and no conjunction, it's called a comma splice. Some people consider this a type of run-on sentence, while other people think of it as a punctuation error.


1 Answers

You can avoid adding commas to each string in the list by deferring the formatting to print time. Join all the items excluding the last on ', ', then use formatting to insert the joined string with the last item conjuncted by and:

listed.append(inputed) ... print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1])) 

Demo:

>>> listed = ['a', 'b', 'c', 'd'] >>> print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1])) a, b, c, and d 
like image 157
Moses Koledoye Avatar answered Sep 19 '22 11:09

Moses Koledoye