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.)
source to share
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.
source to share
"{} 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'
source to share