Automate the boring stuff with Python: Comma Code

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

    I didn't dig through all the answers but I did see someone suggested using join. I agree but since this question didn't come in the book before learning joins my answer was this.

    def To_String(my_list)
        try:
            for index, item in enumerate(my_list):
                if index == 0:                       # at first index
                    myStr = str(item) + ', '
                elif index < len(my_list) - 1:       # after first index
                    myStr += str(item) + ', '
                else:
                    myStr += 'and ' + str(item)      # at last index
            return myStr  
    
        except NameError:
            return 'Your list has no data!'
    
    spam = ['apples', 'bananas', 'tofu', 'cats']
    
    my_string = To_String(spam)
    
    print(my_string)
    

    Result:

    apples, bananas, tofu, and cats
    

提交回复
热议问题