Python

Python Count Characters in String

Python provides many built-in functions and count() is one of them. As its name recommends it will return the total sum of a given object in a Python string. The counting initiates from the starting index of the string till the end. You can also specify the start and end string index from where you wish the search to initiate. So, our today’s discussion topic is how python counts characters in the string.

Example 1:

In our first example code, we can count the existence of an item in strings using the count() function. It will provide how many times the value comes in the specified string. The str.cout() method makes easy work of counting string characters. For example, if you wanted to only count a single character, this would be a handy, useful, and effective approach. If you would like to count “A” from our given string, we could use the str.cout() method to accomplish this task. Let’s take a deep glance at how it works. Here, we use a print statement and pass the count() function as an argument that counts “a” in the specified string.

print(‘Alex had a little cat’.count('a'))

Execute the code file and check how the count() function counts the occurrence of a character in the python string.

Example 2:

In our previous example code, we use the count() method to compute the existence of a character in the given string. But here we use collection.counter() to perform the same task. The task is the same but this time we use a different approach to accomplish this. Counter exists in the collections module and is a dict subclass. It holds the objects as dictionary keys, and their existences are kept as dictionary elements. Rather than raising an error, it yields a zero count for missing elements. Come, let’s check the working of the collection.counter() via Spyder Compiler. We first import the counter from the collection module. After this, we initialize our first python string and then use a count function and feed our string as an argument to count “o” in the given string.

from collections import Counter

test_str = "John is a good boy"

coun_str= Counter(test_str)

print(count.st[‘o’])

Execute the code file and check how the counter.collection() function counts the occurrence of a character in the Python string.

Example 3:

Let’s move forward to our next example code where we use a regular expression to find the existence of characters in the Python string. A regular expression is a focused syntax held in a format that helps you to search the strings or set of strings by matching that format. We want to ingress the re module to work with these expressions. Here, we use the findall() function to fix this issue.

However, the findall() module is used to find “all” incidences that match a specified format. Alternatively, the search() module will only return the first incidence that matches the specified pattern. Come let’s check the working of findall() via Spyder Compiler. We first import the counter from the collection module. After this, we initialize our first python string and then use a findall() function and feed our string as an argument to count “e” in the given string.

import re

test_str = "Sam loves to drink coffee"

print(len(re.findall("e", test_str)))

Execute the code file and check how the counter.collection() function counts the occurrence of a character in the python string.

Example 4:

Here we use the lambda function which not only counts incidences from the specified string but can also work when we are working with a list of sub-strings. Come let’s check the working of the lambda() function.

sentence = [‘p’, ‘yt’, ‘h’, ‘on’, ‘bes’, ‘t’, ‘c’, ‘od’, ‘e’]

print(sum(map(lambda x: 1 if ‘t’ in x else 0, sentence)))

Again, run the lambda code and check the output on the console screen.

Conclusion:

In this tutorial, we have discussed four different methods to count the characters in the python string. You learned how to do this using the count(), counter(), findall(), and lambda() methods. All these methods are very helpful, easy to comprehend, and easy to code.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content