>>> spam = ['apples', 'bananas', 'tofu', 'cats']
>>> print(', '.join(spam[:-2] + [spam[-2] + ' and ' + spam[-1]]))
apples, bananas, tofu and cats
The comma after tofu
should not exist.
Steps:
', '.join(...)
creates a comma-separated string of the values contained inspam
spam[:-2]
slicesspam
and creates a sublist from the first to the second-to-last item. Have a look at python's slice notation.[spam[-2] + ' and ' + spam[-1]]
creates a list containing:spam
's second-to-last item ('tofu'
), the word'and'
andspam
's last item ('cats'
). Creating a list is necessary because python doesn't know how to concatenate a list + another type of object. We can only concatenates lists.
Edit: Oxford Comma is a thing, apparently. Well, hooray english.
>>> spam = ['apples', 'bananas', 'tofu', 'cats']
>>> print(', '.join(spam[:-1] + [' and ' + spam[-1]]))
apples, bananas, tofu, and cats