Python string.join ( list ) last entry with “and”

前端 未结 4 1403
迷失自我
迷失自我 2021-01-18 19:57

What is an elegant way to join a list of sentence parts so that the result is \"a, b, and c\" where the list is [ \'a\', \'b\', \'c\' ]? Specifying

4条回答
  •  一向
    一向 (楼主)
    2021-01-18 20:55

    "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
    
    
    In [25]: l =[ 'a']
    
    In [26]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
    Out[26]: 'a'
    
    In [27]: l =[ 'a','b']
    
    In [28]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
    Out[28]: 'a and b'
    
    In [29]: l =[ 'a','b','c']
    
    In [30]: "{} and {}".format(",".join(l[:-1]),l[-1]) if len(l) > 1 else l[0]
    Out[30]: 'a,b and c'
    

提交回复
热议问题