Reputation: 43
How do I add a comma between every list element and an "and" between the last 2 so the output would be:
My cats are: Bella
My cats are: Bella and Tigger
My cats are: Bella, Tigger and Chloe
My cats are: Bella, Tigger, Chloe and Shadow
Here're the two functions I have, both don't work properly:
Example = ['Bella', 'Tigger', 'Chloe', 'Shadow']
def comma_and(list):
for i in range(len(list)):
print('My Cats are:',', '.join(list[:i]), 'and', list[-1],)
def commaAnd(list):
for i in range(len(list)):
print('My Cats are:',', '.join(list[:i]), list.insert(-1, 'and'))
My current output is:
>> comma_and(Example)
My Cats are: and Shadow
My Cats are: Bella and Shadow
My Cats are: Bella, Tigger and Shadow
My Cats are: Bella, Tigger, Chloe and Shadow
>> commaAnd(Example)
My Cats are: None
My Cats are: Bella None
My Cats are: Bella, Tigger None
My Cats are: Bella, Tigger, Chloe None
Upvotes: 1
Views: 2962
Reputation: 403
The condition where there is only one cat in the list needs special handling. What I'll do is, first join the elements of list starting from index 0 till second last element with a comma.
', '.join(list[:-1])
does this part. The point worth noting here is if the list has only one cat then list[:-1]
will be an empty list and thus ', '.join(list[:-1])
will be an empty string. So, I just took advantage of this empty string in finding out if the list has only one cat.
def comma_and(list):
cats = ', '.join(list[:-1])
if cats:
cats += ' and ' + list[-1]
else:
cats = list[0]
print("My cats are: " + cats)
Upvotes: 1
Reputation: 387607
The first solution is already almost what you want. You just have to make sure that you don’t always take the last element from the list (-1
) but the last item from the current iteration:
>>> for i in range(len(list)):
print('My Cats are:',', '.join(list[:i]), 'and', list[i])
My Cats are: and Bella
My Cats are: Bella and Tigger
My Cats are: Bella, Tigger and Chloe
My Cats are: Bella, Tigger, Chloe and Shadow
And then you just need to special-case the first iteration when there is only a single item:
>>> for i in range(len(list)):
if i == 0:
cats = list[0]
else:
cats = ', '.join(list[:i]) + ' and ' + list[i]
print('My Cats are:', cats)
My Cats are: Bella
My Cats are: Bella and Tigger
My Cats are: Bella, Tigger and Chloe
My Cats are: Bella, Tigger, Chloe and Shadow
Upvotes: 1