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

前端 未结 10 1049
借酒劲吻你
借酒劲吻你 2020-12-18 22:19

I have created this function to parse the list:

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


def coma(abc):
    for i in abc[0:-         


        
相关标签:
10条回答
  • 2020-12-18 23:04

    Might as well round out the solutions with a recursive example.

    >>> listy = ['item1', 'item2','item3','item4','item5', 'item6']
    >>> def foo(a):
        if len(a) == 1:
            return ', and ' + a[0]
        return a[0] + ', ' + foo(a[1:])
    
    >>> foo(listy)
    'item1, item2, item3, item4, item5, , and item6'
    >>> 
    
    0 讨论(0)
  • 2020-12-18 23:05

    One more different way to do:

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

    first way:

    print(', '.join('and, ' + listy[item] if item == len(listy)-1 else listy[item]
    for item in xrange(len(listy))))
    
    output >>> item1, item2, item3, item4, item5, and, item6
    

    second way:

    print(', '.join(item for item in listy[:-1]), 'and', listy[-1])
    
    output >>> (item1, item2, item3, item4, item5, 'and', 'item6')
    
    0 讨论(0)
  • 2020-12-18 23:05

    Correction for Craig’s answer above for a 2-element list (I’m not allowed to comment):

    def oxford_comma_join(l):
        if not l:
            return ""
        elif len(l) == 1:
            return l[0]
        elif len(l) == 2:
            return l[0] + " and " + l[1]
        else:
            return ', '.join(l[:-1]) + ", and " + l[-1]
    
    print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))
    
    print(oxford_comma_join(['i1', 'i2']))
    

    Results:

    item1, item2, item3, item4, item5, and item6
    i1 and i2
    
    0 讨论(0)
  • 2020-12-18 23:05

    I cannot take full credit but if you want succinct -- I modified RoadieRich's answer to use f-strings and also made it more concise. It uses the solution by RootTwo given in a comment on that answer:

    def join(items):
        *start, last = items
        return f"{','.join(start)}, and {last}" if start else last
    
    0 讨论(0)
提交回复
热议问题