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

前端 未结 10 1080
借酒劲吻你
借酒劲吻你 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: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
    

提交回复
热议问题