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()
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.
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.
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.”
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With