Automate the boring stuff with Python: Comma Code

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

    Others have given great one-liner solutions, but a good way to improve your actual implementation - and fix the fact that it does not work when elements are repeated - is to use enumerate in the for loop to keep track of the index, rather than using index which always finds the first occurrence of the target.

    for counter, element in enumerate(list):
        new_string = new_string + str(element)
        if counter == (len(list)-2):
            ...
    

提交回复
热议问题