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