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

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

    Assuming len(words)>2, you can join the first n-1 words using ', ', and add the last word using standard string formatting:

    def join_words(words):
        if len(words) > 2:
            return '%s, and %s' % ( ', '.join(words[:-1]), words[-1] )
        else:
            return ' and '.join(words)
    
    0 讨论(0)
  • 2021-01-18 20:39
    L = ['a','b','c']
    
    if len(L)>2:
        print ', '.join(L[:-1]) + ", and " + str(L[-1])
    elif len(L)==2:
        print ' and '.join(L)
    elif len(L)==1:
        print L[0]
    

    Works for lengths 0, 1, 2, and 3+.

    The reason I included the length 2 case is to avoid commas: a and b.

    If the list is length 1, then it just outputs a.

    If the list is empty, nothing is outputted.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题