Python help needed

MRAB python at mrabarnett.plus.com
Wed Aug 7 19:18:02 EDT 2019


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']
> print(myList(spam))
> 
> #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?
> https://pastebin.com/JCXisAuz
> 
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[0].




More information about the Python-list mailing list