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

前端 未结 4 1402
迷失自我
迷失自我 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)
    

提交回复
热议问题