'Add 'and' before the last item in a string list
Okay so I'm trying to make a function that will take a list of items and return (not print!) a string of that list, separated by commas with an 'and' before the last item in the list. My script so far looks like this:
rose1 = Thing("red rose", "flowerbox")
rose2 = Thing("pink rose","garden")
rose3 = Thing("white rose", "vase")
def text_list(things):
"""Takes a sequence of Things and returns a formatted string that describes all of the things.
Things -> string"""
names=[o.name for o in things]
if len(names) == 0:
return 'nothing'
elif len(names) == 2:
names = ' and the '.join(names)
return 'the ' + names
else: #Here's where I need help!
names = ', the '.join(names)
return 'the ' + names
So at this point the function returns "the red rose, the pink rose, the white rose" which is great, but I need that last "and" to be put in between the pink rose and the white rose, and I can't use print. Any help? This is probably simple and I'm just missing it entirely OTL
Solution 1:[1]
You can do it in a single line:
print(', '.join([*lst[:-1], f'and {lst[-1]}']))
For example:
a_list = ['a', 'b', 'c']
print(', '.join([*a_list[:-1], f'and {a_list[-1]}']))
This produces the result
a, b, and c
This will of course won't give the desired results if the list consists of a single item or the empty list.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Walker |
