-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
  • 9,280
  • 9
  • 43
  • 57

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
  • 20,604
  • 6
  • 33
  • 46
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'
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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
  • 673
  • 5
  • 20