Python help needed
Am 08.08.19 um 01:18 schrieb MRAB:
> On 2019-08-07 21:36, Kuyateh Yankz wrote:
>> #trying to write a function that takes a list value as an argument and
>> returns a string with all the items separated by a comma and a space,
>> with and inserted before the last item. For example, passing the
>> previous spam list to the function would return 'apples, bananas,
>> tofu, and cats'. But your function should be able to work with any
>> list value passed to it.
>> def myList(aParameter): #defined
>> ???? finalList = 
>> ???? for i in range(len(aParameter)-1): #targeting the last item in
>> the list
>> ?????? finalList.append('and '+ aParameter[-1]) #Removes the last item
>> in the list, append the last item with THE and put it back, then put
>> it into the FINAL LIST FUNCTION.
>> ???? return finalList
>> spam = ['apples', 'bananas', 'tofu', 'cats']
>> #Got up to this point, still couldn't get rid of the '' around the
>> items and the . I tried (','.join()) but could not get there.
>> #Am I on the wrong path or there's a quick fix here?
> There's a nice way of doing it using str.join. However, you do need to
> special-case when there's only 1 item.
> Start with a list:
> >>> spam = ['apples', 'bananas', 'tofu', 'cats']
> The last item will be have an 'and', so let's remove that for the moment:
> >>> spam[ : -1]
> ['apples', 'bananas', 'tofu']
> Join these items together with ', ':
> >>> ', '.join(spam[ : -1])
> 'apples, bananas, tofu'
> Now for the last item:
> >>> ', '.join(spam[ : -1]) + ' and ' + spam[-1]
> 'apples, bananas, tofu and cats'
> For the special case, when len(spam) == 1, just return spam.
I think the special case treatment could be avoided.
First: Join all items with ' and '
Second: Replace all ' and ' with ', ' except the last
>>> spam = ['apples', 'bananas', 'tofu', 'cats']
>>> s = " and ".join(spam)
>>> s.replace(" and ", ", ", len(spam) - 2) # except the last
'apples, bananas, tofu and cats'
Or as a one liner:
" and ".join(spam).replace(" and ", ", ", len(spam) - 2)
It works also for a single item list:
>>> spam = ['apples']