Acapla
Acapla

Reputation: 33

How to add "and" before the last element of a list?

I'm making this program and it requires a list to be printed out, I would prefer if the list were a little more correct. I was wondering if it were possible to add an "and" before the last element of a list to make it look right. Thanks.

  def inputEat(self):
        input('What would you like to eat? Your choices are {}.'.format(', '.join(healthItems)))
        Fighter.Health(x)
        if self.health >= 100:
            self.health = 100`

Upvotes: 1

Views: 1104

Answers (2)

khelwood
khelwood

Reputation: 59112

You could have a function to construct the joined list the way you want:

def join_and(items):
    return ', '.join(items[:-1]) + ' and '+items[-1]

That is, join all the items except the last with a comma, and then add 'and' before the last item. (Feel free to add an Oxford comma at your discretion.)

>>> join_and(['alpha', 'beta', 'gamma'])
'alpha, beta and gamma'

If you want the function to give an appropriate result for a list of length 1 or 0, you could do something like this:

def join_and(items):
    if len(items)==0:
        return ''
    if len(items)==1:
        return items[0]
    return ', '.join(items[:-1]) + ' and '+items[-1]

Upvotes: 4

harshil9968
harshil9968

Reputation: 3244

Try this:

  • Join all the items like you were doing, except the last one.
  • Explicitly concatenate the last item with and.

input('What would you liketo eat? Your choices are {}.'.format( ', '.join( healthItems[:-1]) + ' and '+healthItems[-1]))

Upvotes: 1

Related Questions