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

后端 未结 8 1613
一向
一向 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

    One liner. Just concatenate all but the last element with , as the delimiter. Then just append & and then the last element finally to the end.

    print ', '.join(lst[:-1]) + ' & ' + lst[-1]
    

    If you wish to handle empty lists or such:

    if len(lst) > 1:
        print ', '.join(lst[:-1]) + ' & ' + lst[-1]
    elif len(lst) == 1:
        print lst[0]
    
    0 讨论(0)
  • 2020-11-28 16:24

    You can simply use Indexng and F-strings (Python-3.6+):

    In [1]: l=['Jim','Dave','James','Laura','Kasra']                                                                                                                                                            
    
    In [3]: ', '.join(l[:-1]) + f' & {l[-1]}'                                                                                                                                                                      
    
    Out[3]: 'Jim, Dave, James, Laura & Kasra'
    
    0 讨论(0)
提交回复
热议问题