How to join list in Python but make the last separator different?

后端 未结 8 1640
一向
一向 2020-11-28 15:28

I\'m trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g.

         


        
8条回答
  •  执笔经年
    2020-11-28 16:04

    It looks like while I was working on my answer, someone may have beaten me to the punch with a similar one. Here's mine for comparison. Note that this also handles cases of 0, 1, or 2 members in the list.

    # Python 3.x, should also work with Python 2.x.
    def my_join(my_list):
        x = len(my_list)
        if x > 2:
            s = ', & '.join([', '.join(my_list[:-1]), my_list[-1]])
        elif x == 2:
            s = ' & '.join(my_list)
        elif x == 1:
            s = my_list[0]
        else:
            s = ''
        return s
    
    assert my_join(['Jim', 'Jack', 'John']) == 'Jim, Jack, & John'
    assert my_join(['Jim', 'Jack']) == 'Jim & Jack'
    assert my_join(['Jim',]) == 'Jim'
    assert my_join([]) == ''
    

提交回复
热议问题