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

What's an elegant way to join a list of parts of a sentence so that the result is "a, b and c", where list

is - [ 'a', 'b', 'c' ]

? The hint just ', '.join()

reaches only "a, b, c".

(Also, I've done some searches on this, but obviously I'm not trying to write phrases because I haven't come up with anything other than listing the list itself.)

+3


source to share


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 that I have included the case of length 2 - is to avoid commas: a and b

.



If the list is 1 in length, it just prints a

.

If the list is empty, nothing is output.

+4


source


Assuming len(words)>2

you can concatenate the first words n-1

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)

      

+1


source


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

      

+1


source


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

      

0


source







All Articles