Reputation: 33
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
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
Reputation: 3244
Try this:
input('What would you liketo eat? Your choices are {}.'.format( ', '.join( healthItems[:-1]) + ' and '+healthItems[-1]))
Upvotes: 1