Joining words together with a comma, and “and”

后端 未结 6 1660
Happy的楠姐
Happy的楠姐 2020-12-10 02:10

I\'m working through \'Automate the Boring Stuff with Python\'. I can\'t figure out how to remove the final output comma from the program below. The goal is to keep promptin

6条回答
  •  醉酒成梦
    2020-12-10 02:30

    I would do it using an f-string (a formatted string literal, available in Python 3.6+):

    def grammatically_join(words, oxford_comma=False):
        if len(words) == 0:
            return ""
        if len(words) == 1:
            return listed[0]
        if len(words) == 2:
            return f"{listed[0]} and {listed[1]}"
        return f'{", ".join(words[:-1])}{"," if oxford_comma else ""} and {words[-1]}'
    

    If you don't need the Oxford comma, then you can simplify the code and remove the extra edge case for len(words) == 2:

    def grammatically_join(words):
        if len(words) == 0:
            return ""
        if len(words) == 1:
            return listed[0]
        return f'{", ".join(words[:-1])} and {words[-1]}'
    

提交回复
热议问题