Automate the boring stuff with Python: Comma Code

前端 未结 29 974
深忆病人
深忆病人 2021-02-03 16:17

Currently working my way through this beginners book and have completed one of the practice projects \'Comma Code\' which asks the user to construct a program which:

29条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 16:33

    Use str.join() to join a sequence of strings with a delimiter. If you do so for all words except for the last, you can insert ' and ' there instead:

    def list_thing(words):
        if len(words) == 1:
            return words[0]
        return '{}, and {}'.format(', '.join(words[:-1]), words[-1])
    

    Breaking this down:

    • words[-1] takes the last element of a list. words[:-1] slices the list to produce a new list with all words except the last one.

    • ', '.join() produces a new string, with all strings of the argument to str.join() joined with ', '. If there is just one element in the input list, that one element is returned, unjoined.

    • '{}, and {}'.format() inserts the comma-joined words and the last word into a template (complete with Oxford comma).

    If you pass in an empty list, the above function will raise an IndexError exception; you could specifically test for that case in the function if you feel an empty list is a valid use-case for the function.

    So the above joins all words except the last with ', ', then adds the last word to the result with ' and '.

    Note that if there is just one word, you get that one word; there is nothing to join in that case. If there are two, you get 'word1 and word 2'. More words produces 'word1, word2, ... and lastword'.

    Demo:

    >>> def list_thing(words):
    ...     if len(words) == 1:
    ...         return words[0]
    ...     return '{}, and {}'.format(', '.join(words[:-1]), words[-1])
    ...
    >>> spam = ['apples', 'bananas', 'tofu', 'cats']
    >>> list_thing(spam[:1])
    'apples'
    >>> list_thing(spam[:2])
    'apples, and bananas'
    >>> list_thing(spam[:3])
    'apples, bananas, and tofu'
    >>> list_thing(spam)
    'apples, bananas, tofu, and cats'
    

提交回复
热议问题