What is the preferred way to count the number of ocurrences of a certain character in a string?

前端 未结 6 1492
花落未央
花落未央 2021-01-20 15:27

How do I do this without string.count(), because it is listed as deprecated in Python v2.7.3 documentation?

I am unable to find what I should use instea

6条回答
  •  借酒劲吻你
    2021-01-20 16:16

    Without using count you can do this:

    def my_count(my_string, key_char):
        return sum(c == key_char for c in my_string)
    

    Result:

    >>> my_count('acavddgaaa','a')
    5
    

提交回复
热议问题