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

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

    Here's a simple one that also works for empty or 1 element lists:

    ' and '.join([', '.join(mylist[:-1])]+mylist[-1:])
    

    The reason it works is that for empty lists both [:-1] and [-1:] give us an empty list again

提交回复
热议问题