Count letter in word python

The other answers show what’s wrong with your code. But there’s also a built-in way to do this, if you weren’t just doing this for an exercise:

>>> 'banana'.count('a')
3

Danben gave this corrected version:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

Here are some other ways to do it, hopefully they will teach you more about Python!

Similar, but shorter for loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:

def count_letters(word, char):
  count = 0
  for c in word:
    count += (char == c)
  return count

Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn’t match char and 1 if it does, and then sums them:

def count_letters(word, char):
  return sum(char == c for c in word)

The next one filters out all the characters that don’t match char, and counts how many are left:

def count_letters(word, char):
  return len([c for c in word if c == char])

Given a string, the task is to count the frequency of a single character in that string. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters. 

Method #1 : Naive method Iterate the entire string for that particular character and then increase the counter when we encounter the particular character. 

Python3

test_str = "GeeksforGeeks"

count = 0

for i in test_str:

    if i == 'e':

        count = count + 1

print ("Count of e in GeeksforGeeks is : "

                            + str(count))

Output

Count of e in GeeksforGeeks is : 4

  Method #2 : Using count() Using count() is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular. 

Python3

test_str = "GeeksforGeeks"

counter = test_str.count('e')

print ("Count of e in GeeksforGeeks is : "

                        + str(counter))

Output

Count of e in GeeksforGeeks is : 4

  Method #3 : Using collections.Counter() This is the lesser known method to get the occurrence of the element across any container in Python. This also performs the task similar to above two method, just is a function of a different library i.e collections. 

Python3

from collections import Counter

test_str = "GeeksforGeeks"

count = Counter(test_str)

print ("Count of e in GeeksforGeeks is : "

                    + str(count['e']))

Output

Count of e in GeeksforGeeks is : 4

  Method #4 : Using lambda + sum() + map() Lambda functions, along with sum() and map() can achieve this particular task of counting the total occurrences of particular element in a string. This uses sum() to sum up all the occurrences obtained using map(). 

Python3

test_str = "GeeksforGeeks"

count = sum(map(lambda x : 1 if 'e' in x else 0, test_str))

print ("Count of e in GeeksforGeeks is : "

                            + str(count))

Output

Count of e in GeeksforGeeks is : 4

  Method #5 : Using re + findall() Regular Expressions can help us to achieve many coding tasks related to strings. They can also facilitate us in achieving the task of finding the occurrence of element in string. 

Python3

import re

test_str = "GeeksforGeeks"

count = len(re.findall("e", test_str))

print ("Count of e in GeeksforGeeks is : "

                            + str(count))

Output

Count of e in GeeksforGeeks is : 4

Method #6: Using operator.countOf() method

Python3

import operator as op

test_str = "GeeksforGeeks"

counter = op.countOf(test_str, "e")

print("Count of e in GeeksforGeeks is : "

      + str(counter))

Output

Count of e in GeeksforGeeks is : 4

Time and Space Complexity for all the approaches is same:

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #7:Using reduce()

  1. Import the reduce() function from the functools module.
  2. Initialize the input string and the character to count.
  3. Define a lambda function that takes two arguments: an accumulator acc and a character c. The lambda function checks if the current character c is equal to the character to count char_to_count. If it is, it increments the accumulator acc by 1. If it isn’t, it just returns acc unchanged.
  4. Apply the reduce() function to the input string test_str, using the lambda function and an initial value of 0. The reduce() function applies the lambda function to each character in the string test_str, starting with the initial value 0. The final value of the accumulator acc is the count of the character char_to_count in the string test_str.
  5. The result is stored in the count variable.
  6. Print the result using an f-string to format the output.

Python3

from functools import reduce

test_str = "GeeksforGeeks"

char_to_count = 'e'

count = reduce(lambda acc, c: acc + 1 if c == char_to_count else acc, test_str, 0)

print(f"Count of {char_to_count} in {test_str} is: {count}")

Output

Count of e in GeeksforGeeks is: 4

The time complexity of this code is O(n), where n is the length of the input string test_str. This is because we iterate over each character in the string exactly once.

The auxiliary space of this code is O(1), because we only use a constant amount of additional space to store the input string, the character to count, the accumulator acc, and the lambda function. Therefore, the space used does not depend on the length of the input string.

Counter is definitely the way to go (and I’ve upvoted Jaime’s answer).

If you want to do it yourself and iterate only once, this should work :

d={}
for l in s:
        d[l] = d.get(l,0) + 1

There might be a short/more pythonic way to do so but it works…

Edit :
I must confess that Jaime’s comment to this answer surprised me but I’ve just tested this code :

from profilehooks import profile

s="qwertyuiopasdfghjklzxcvbnm"

@profile
def function1(s):
        d={}
        for l in s:
                d[l] = d.get(l,0)+1
        return d

@profile
def function2(s):
        return dict((char_, s.count(char_)) for char_ in set(s))

for i in xrange(0,200):
        function1(s*i)
        function2(s*i)

And the results can hardly be contested :

*** PROFILER RESULTS ***
function2 (./fsdhfsdhjk.py:13)
function called 200 times

         10948 function calls in 0.161 seconds

   Ordered by: cumulative time, internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      200    0.083    0.000    0.161    0.001 fsdhfsdhjk.py:13(function2)
     5374    0.033    0.000    0.077    0.000 fsdhfsdhjk.py:15(<genexpr>)
     5174    0.044    0.000    0.044    0.000 {method 'count' of 'str' objects}
      200    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        0    0.000             0.000          profile:0(profiler)



*** PROFILER RESULTS ***
function1 (./fsdhfsdhjk.py:6)
function called 200 times

         517800 function calls in 2.891 seconds

   Ordered by: cumulative time, internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      200    1.711    0.009    2.891    0.014 fsdhfsdhjk.py:6(function1)
   517400    1.179    0.000    1.179    0.000 {method 'get' of 'dict' objects}
      200    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        0    0.000             0.000          profile:0(profiler)

TL;DR
Jaime’s solution (function2) is 18 times faster than mine (function1).

  1. Use the count() Function to Count the Number of a Characters Occuring in a String in Python
  2. Use the collections.Counter to Count the Occurrences of a Character in a String in Python
  3. Use Regular Expressions to Count the Occurrences of a Character in a String in Python
  4. Use the defaultdict to Count the Occurrences of a Character in a String in Python
  5. Use the pandas.value_counts() to Count the Occurrences of a Character in a String in Python
  6. Use a lambda Expression to Count the Occurrences of a Character in a String in Python
  7. Use the for Loop to Count the Occurrences of a Character in a String in Python

Count Occurrences of a Character in a String in Python

In Programming, a string is a sequence of characters.

This tutorial will introduce how to count the number of occurrences of a character in a String in Python.

Use the count() Function to Count the Number of a Characters Occuring in a String in Python

We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

For example,

print('Mary had a little lamb'.count('a'))

Output:

Remember, upper and lower cases are treated as different characters. A and a will be treated as different characters and have different counts.

Use the collections.Counter to Count the Occurrences of a Character in a String in Python

A Counter is a dictionary subclass present in the collections module. It stores the elements as dictionary keys, and their occurrences are stored as dictionary values. Instead of raising an error, it returns a zero count for missing items.

For example,

from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print(counter['a'])

Output:

It is a better choice when counting for many letters as counter calculates all the counts one time. It is a lot faster than the count() function.

Use Regular Expressions to Count the Occurrences of a Character in a String in Python

A regular expression is a specialized syntax held in a pattern that helps find the strings or set of strings by matching that pattern. We import the re module to work with regular expressions.

We can use the findall() function for our problem.

For example,

import re
my_string = "Mary had a little lamb"
print(len(re.findall("a", my_string)))

Output:

Use the defaultdict to Count the Occurrences of a Character in a String in Python

Defaultdict is present in the collections module and is derived from the dictionary class. Its functionality is relatively the same as that of dictionaries except that it never raises a KeyError, as it provides a default value for the key that never exists.

We can use it to get the occurrences of a character in a string as shown below.

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1
    
print(chars['a'])
print(chars['t'])
print(chars['w']) # element not present in the string, hence print 0

Output:

Use the pandas.value_counts() to Count the Occurrences of a Character in a String in Python

We can use the pandas.value_counts() method to get the occurrences of all the characters present in the provided string. We need to pass the string as a Series object.

For example,

import pandas as pd
phrase = "Mary had a little lamb"
print(pd.Series(list(phrase)).value_counts())

Output:

     4
a    4
l    3
t    2
e    1
b    1
h    1
r    1
y    1
M    1
m    1
i    1
d    1
dtype: int64

It returns the occurrences of all characters in a Series object.

Use a lambda Expression to Count the Occurrences of a Character in a String in Python

lambda functions can not only count occurrences from the given string, but can also work when we have the string, as a list of sub-strings.

See the following code.

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
print(sum(map(lambda x : 1 if 'a' in x else 0, sentence)))

Output:

Use the for Loop to Count the Occurrences of a Character in a String in Python

We iterate over the string, and if the element equals the desired character, the count variable is incremented till we reach the end of the string.

For example,

sentence = 'Mary had a little lamb'    
count = 0
for i in sentence:
    if i == "a":
        count = count + 1
print(count)

Output:

We can see another way of using this method with the sum() function can be seen below.

my_string = "Mary had a little lamb"
print(sum(char == 'a' for char in my_string))

Output:

Codecademy Forums

Loading

Понравилась статья? Поделить с друзьями:
  • Count in excel with duplicates
  • Count in excel for text
  • Count in excel by name
  • Count in excel but not duplicates
  • Count in between dates excel