Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:
I was not satisfied with any of the solutions because none handle the case with or
, e.g. apples, bananas, or berries
def oxford_comma(words, conjunction='and'):
conjunction = ' ' + conjunction + ' '
if len(words) <= 2:
return conjunction.join(words)
else:
return '%s,%s%s' % (', '.join(words[:-1]), conjunction, words[-1])
Otherwise, this solution is more-or-less identical to the one provided by @PM2Ring