-2

here's my code

spam = ['apples', 'bananas', 'lemons']

def funcc(spam):
    for i in range(len(spam) - 1):
        print(spam[i], ',')
    print('and', spam[-1])

I need to make a function which returns a string with all the items separated by a comma and a space with 'and' inserted before the last item. But my function should be able to work with any list value passed on it. I don't need the full code to resolve my problem, just asking for techniques to solve this task!

Kev1n91
  • 3,553
  • 8
  • 46
  • 96
David
  • 1
  • 2

3 Answers3

2

You can make use of function join from str. You pass a list as a parameter and returns the list joined as a single string.

Example:

spam = ['apples', 'bananas', 'lemons']
', '.join(spam[:-1])

Output:

'apples, bananas'

Then you can concatenate the previous string with the last element using ' and '.

', '.join(spam[:-1]) + ' and ' + spam[-1]

Output:

'apples, bananas and lemons'
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
1

You may use str.join() to join the list and explicitly add "and" for the last element using str.format() as:

spam = ['apples', 'bananas', 'lemons']
#  Join all elements with `, ` excluding last element
#                                               v    
new_string = '{} and {}'.format(', '.join(spam[:-1]), spam[-1])
#                 ^  explicitly add `"and"` to the joined string 
#                    with the last element

Value hold by new_string will be:

'apples, bananas and lemons'

Explanation:

Value returned by str.join()

>>> ', '.join(spam[:-1])
'apples, bananas'

Hence, values passed to str.format() will be:

>>> '{} and {}'.format('apples, bananas', 'lemons')
'apples, bananas and lemons'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • @Downvoter Whenever you downvote any answer, please also leave the comment. May be based on your opinion I could have wrote better answers (including this one and the answers I will write in future) :) – Moinuddin Quadri Nov 27 '16 at 12:17
0

I think this is more a genereous question like it is related to python. First you should think about what you want to do, in your case you want to seperate your items by commas, so you need to iterate over them like you did correctly. Now you must think about a way to put the comma after every word and save it in a new variable that holds the string you want at the end. When it comes down to memory management you should think about the needed space for the output string - e.g you have 3 variables in your current list, but with the commas and the 'and' comes new values within. Python is very easy to handle here with insert or join Furthermore, you know that between the second last and the last you want the word 'and', thus you you must think of this special case in a form of a kind of condition (if-statement). Note that this is an approach that do not refer to the usage of python directly.

Kev1n91
  • 3,553
  • 8
  • 46
  • 96