Neil C. Obremski
Neil C. Obremski

Reputation: 20264

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

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. )

Upvotes: 7

Views: 4177

Answers (5)

dedebenui
dedebenui

Reputation: 21

Here is a robust oneliner that works with any number of elements, even 0.

", ".join(l[:-2] + [" and ".join(l[-2:])])

using range index : everywhere frees you from having to handle special cases.

Note: it only works with lists because of the + operator.

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19733

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

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

"{} 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'

Upvotes: 1

AureliusPhi
AureliusPhi

Reputation: 433

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.

Upvotes: 6

shx2
shx2

Reputation: 64318

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)

Upvotes: 2

Related Questions