-1

I have this list:

sampleList=['a','b','c','d']

I need to display the list elements as follows:

a, b, c and d

I tried to join ',' with each list element. However I couldn't get the expected result.

','.join(sampleList)

Each list element is separated by comma and keyword 'and' prior to last element like a, b, c and d.

petezurich
  • 7,683
  • 8
  • 34
  • 51

3 Answers3

1

There's not built-in way to do that. You have to DIY

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

Output:

>>> sampleList = ['a', 'b', 'c', 'd']
>>> ', '.join(sampleList[:-1]) + ' and ' + str(sampleList[-1])
'a, b, c and d'
>>>
rdas
  • 18,048
  • 6
  • 31
  • 42
0

Try this code using str.join, reversing with [::-1] and str.replace (it's kinda a hack):

>>> sampleList=['a','b','c','d']
>>> s = ', '.join(sampleList)
>>> s[::-1].replace(' ,', ' dna ', 1)[::-1]
'a, b, c and d'
>>> 
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
0

For this you can do the same for n-1 elements and concatenate the last element by 'and':

L=['a','b','c','d']
l=L[:-1] #get all except the last element
st=l.join(',')
sf= st+' and '+L[-1]
#sf=a,b,c and d
Tojra
  • 653
  • 4
  • 20