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

前端 未结 4 1396
迷失自我
迷失自我 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:39

    l = ['a','b','c']
    if len(l) > 1:
        print ",".join(k[:-1]) +  " and " + k[-1]
    else:print l[0]
    

    exapmles:

    l = ['a','b','c']
    a,b and c
    
    l = ['a','b']
    a and b
    
    l=['a']
    a
    

提交回复
热议问题