Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list into comma-separated string with "and" before the last item - Python 2.7

I have created this function to parse the list:

listy = ['item1', 'item2','item3','item4','item5', 'item6']


def coma(abc):
    for i in abc[0:-1]:
        print i+',',
    print "and " + abc[-1] + '.'

coma(listy)

#item1, item2, item3, item4, item5, and item6.

Is there a neater way to achieve this? This should be applicable to lists with any length.

like image 211
Simon S Avatar asked Aug 16 '16 17:08

Simon S


People also ask

How do I convert a list to a comma-separated string in Python?

Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.

How do you convert a list to a comma-separated string?

The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.

How do you print a list as comma-separated values in Python?

for i, x in enumerate(a): if i: print ',' + str(x), else: print str(x), this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first.

How do you separate a list with commas?

When making a list, commas are the most common way to separate one list item from the next. The final two items in the list are usually separated by "and" or "or", which should be preceeded by a comma. Amongst editors this final comma in a list is known as the "Oxford Comma".


2 Answers

When there are 1+ items in the list (if not, just use the first element):

>>> "{} and {}".format(", ".join(listy[:-1]),  listy[-1])
'item1, item2, item3, item4, item5 and item6'

Edit: If you need an Oxford comma (didn't know it even existed!) -- just use: ", and" instead:

>>> "{}, and {}".format(", ".join(listy[:-1]),  listy[-1])
'item1, item2, item3, item4, item5, and item6'
like image 165
UltraInstinct Avatar answered Oct 18 '22 02:10

UltraInstinct


def oxford_comma_join(l):
    if not l:
        return ""
    elif len(l) == 1:
        return l[0]
    else:
        return ', '.join(l[:-1]) + ", and " + l[-1]

print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))

Output:

item1, item2, item3, item4, item5, and item6

Also as an aside the Pythonic way to write

for i in abc[0:-1]:

is

for i in abc[:-1]:
like image 27
Craig Burgler Avatar answered Oct 18 '22 04:10

Craig Burgler