python counting letters in string without count function

前端 未结 5 1881
眼角桃花
眼角桃花 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:17

    Instead of

    count == count + 1
    

    you need to have

    count = count + 1
    
    0 讨论(0)
  • 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)))
    
    0 讨论(0)
  • 2021-01-22 17:24

    Be careful, you are using count == count + 1, and you must use count = count + 1

    The operator to attribute a new value is =, the operator == is for compare two values

    0 讨论(0)
  • 2021-01-22 17:30

    Although someone else has solved your problem, the simplest solution to do what you want to do is to use the Counter data type:

    >>> from collections import Counter
    >>> letter = 'a'
    >>> myString = 'aardvark'
    >>> counts = Counter(myString)
    >>> print(counts)
    Counter({'a': 3, 'r': 2, 'v': 1, 'k': 1, 'd': 1})
    >>> count = counts[letter]
    >>> print(count)
    3
    

    Or, more succinctly (if you don't want to check multiple letters):

    >>> from collections import Counter
    >>> letter = 'a'
    >>> myString = 'aardvark'
    >>> count = Counter(myString)[letter]
    >>> print(count)
    3
    

    The simplest way to do your implementation would be:

    count = sum(i == letter for i in myString)
    

    or:

    count = sum(1 for i in myString if i == letter)
    

    This works because strings can be iterated just like lists, and False is counted as a 0 and True is counted as a 1 for arithmetic.

    0 讨论(0)
  • 2021-01-22 17:33

    Use filter function like this

    len(filter(lambda x: x==letter, myString))
    
    0 讨论(0)
提交回复
热议问题