python counting letters in string without count function

前端 未结 5 1880
眼角桃花
眼角桃花 2021-01-22 16:54

I am trying to write a program to count the occurrences of a specific letter in a string without the count function. I made the string into a list and set a loop to count but th

5条回答
  •  清酒与你
    2021-01-22 17:19

    Your count is never changing because you are using == which is equality testing, where you should be using = to reassign count. Even better, you can increment with

    count += 1
    

    Also note that else: continue doesn't really do anything as you will continue with the next iteration of the loop anyways. If I were to have to come up with an alternative way to count without using the count function, I would lean towards regex:

    import re
    stringy = "aardvark"
    print(len(re.findall("a", stringy)))
    

提交回复
热议问题