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

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

    "&".join([",".join(my_list[:-1]),my_list[-1]])
    

    I would think would work

    or maybe just

    ",".join(my_list[:-1]) +"&"+my_list[-1]
    

    to handle edge cases where only 2 items you could

    "&".join([",".join(my_list[:-1]),my_list[-1]] if len(my_list) > 2 else my_list)
    

提交回复
热议问题