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

前端 未结 6 1491
花落未央
花落未央 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:14
    sentence = str(input("Write a Sentence: "))
    count = 0
    for word in sentence:
        if word == " ":
        count = count + 1
    print(count+1)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-20 16:22

    The other way can be

    strs.__len__()

    0 讨论(0)
  • 2021-01-20 16:24

    This works fine in 2.7.3

    >>> strs='aabbccddaa'
    >>> strs.count('a')
    4
    
    0 讨论(0)
  • 2021-01-20 16:33

    Use str.count() - it's not listed as deprecated.

    (Python 2.7.3, Python 3.2.3 - both have no notes about being deprecated).

    >>> "test".count("t")
    2
    

    I'll presume you meant string.count() - which is depreciated in favour of the method on string objects.

    The difference is that str.count() is a method on string objects, while string.count() is a function in the string module.

    >>> "test".count("t")
    2
    >>> import string
    >>> string.count("test", "t")
    2
    

    It's clear why the latter has been deprecated (and removed in 3.x) in favour of the former.

    0 讨论(0)
  • 2021-01-20 16:34

    Use len():

    >>> len('abcd')
    4
    
    0 讨论(0)
提交回复
热议问题