Automate the boring stuff with Python: Comma Code

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

    I came up with this solution

    #This is the list which needs to be converted to String
    spam = ['apples', 'bananas', 'tofu', 'cats']
    
    #This is the empty string in which we will append
    s = ""
    
    
    def list_to_string():
        global spam,s
        for x in range(len(spam)):
            if s == "":
                s += str(spam[x])
            elif x == (len(spam)-1):
                s += " and " + str(spam[x])
            else:
                s += ", " + str(spam[x])
        return s
    
    a = list_to_string()
    print(a)
    

提交回复
热议问题