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.
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.
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.
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.
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".
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'
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]:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With