Automate the boring stuff with Python: Comma Code

前端 未结 29 1590
深忆病人
深忆病人 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:54

    My interpretation of the question is such that a single list item would also be the last list item, and as such would need the 'and' inserted before it, as well as a two item list returning both with ', and' between them. Hence no need to deal with single or two item lists seperately, just the first n items, and the last item. I'd also note that while great, a lot of the other items use modules and functions not taught in the Automate the Boring Stuff text by the time the student encounters this question (a student like me had seen join and .format elsewhere, but attempted to only use what had been taught in the text).

    def commacode(passedlist):
        stringy = ''
        for i in range(len(passedlist)-1):
            stringy += str(passedlist[i]) + ', '
            # adds all except last item to str
        stringy += 'and ' + str(passedlist[len(passedlist)-1])
        # adds last item to string, after 'and'
        return stringy
    

    And you could handle the empty list case by:

    def commacode(passedlist):
        stringy = ''
        try:
            for i in range(len(passedlist)-1):
                stringy += str(passedlist[i]) + ', '
                # adds all except last item to str
            stringy += 'and ' + str(passedlist[len(passedlist)-1])
            # adds last item to string, after 'and'
            return stringy
        except IndexError:
            return '' 
            #handles the list out of range error for an empty list by returning ''
    

提交回复
热议问题