Python string.join ( list ) last entry with "and"

Question:

What is an elegant way to join a list of sentence parts so that the result is “a, b, and c” where the list is [ 'a', 'b', 'c' ]? Specifying simply ', '.join() achieves only “a, b, c”.

( Also, I did do a few searches on this but obviously I’m not trying the write phrases because I haven’t come up with anything besides enumerating the list myself. )

Asked By: Neil C. Obremski

||

Answers:

Assuming len(words)>2, you can join the first n-1 words using ', ', and add the last word using standard string formatting:

def join_words(words):
    if len(words) > 2:
        return '%s, and %s' % ( ', '.join(words[:-1]), words[-1] )
    else:
        return ' and '.join(words)
Answered By: shx2
L = ['a','b','c']

if len(L)>2:
    print ', '.join(L[:-1]) + ", and " + str(L[-1])
elif len(L)==2:
    print ' and '.join(L)
elif len(L)==1:
    print L[0]

Works for lengths 0, 1, 2, and 3+.

The reason I included the length 2 case is to avoid commas: a and b.

If the list is length 1, then it just outputs a.

If the list is empty, nothing is outputted.

Answered By: AureliusPhi
"{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]


In [25]: l =[ 'a']

In [26]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
Out[26]: 'a'

In [27]: l =[ 'a','b']

In [28]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
Out[28]: 'a and b'

In [29]: l =[ 'a','b','c']

In [30]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
Out[30]: 'a,b and c'
Answered By: Padraic Cunningham
l = ['a','b','c']
if len(l) > 1:
    print ",".join(k[:-1]) +  " and " + k[-1]
else:print l[0]

exapmles:

l = ['a','b','c']
a,b and c

l = ['a','b']
a and b

l=['a']
a
Answered By: Hackaholic

Another solution:

l = ['a','b','c']
" and ".join((", ".join(l[:-1]),l[-1])) 
Answered By: Hirley Dayan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.