Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 409
Neil C. Obremski Avatar asked Nov 02 '14 21:11

Neil C. Obremski


4 Answers

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.

like image 73
AureliusPhi Avatar answered Sep 19 '22 09:09

AureliusPhi


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)
like image 25
shx2 Avatar answered Sep 21 '22 09:09

shx2


"{} 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'
like image 45
Padraic Cunningham Avatar answered Sep 22 '22 09:09

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
like image 39
Hackaholic Avatar answered Sep 21 '22 09:09

Hackaholic