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

后端 未结 8 1678
一向
一向 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:14

    You could break this up into two joins. Join all but the last item with ", ". Then join this string and the last item with " & ".

    all_but_last = ', '.join(authors[:-1])
    last = authors[-1]
    
    ' & '.join([all_but_last, last])
    

    Note: This doesn't deal with edge cases, such as when authors is empty or has only one element.

提交回复
热议问题