Skip to main content

Count occurrences of a character in string in Python

Hello everyone! Today we are going to see how can we count the occurrences of a character in a given string using Python.

Python provides a library method count which can be used to count the occurrence of a substring in a given string. Below code snippet takes a character as a substring and returns the count of that in the source string.
# Enter the string in which we need to search 
sentence = input("Enter a string\n")
 
# Enter a string/character which needs to be searched
sub_string = input("Enter the substring to search\n")
 
# Getting the count of the sub string in source string - convert both to lowercase if we want to count irrespective of case
count_of_substring = sentence.lower().count(sub_string.lower())
 
# Print the count of the substring in the source string
print('Count of ' + sub_string + ' in ' + sentence + ' is ' + str(count_of_substring))
The output of this program will be as follows -
>> Enter a string
Help is always given at Hogwarts to those who ask for it
>> Enter the substring to search
h
>> Count of h in Help is always given at Hogwarts to those who ask for it is 4
If you do not wish to use the library method and want to implement your own then you can do this as follows -
def character_count(source_string, character):
 
    # Converting source string and character to lower case to make them case insensitive    
    source_string = source_string.lower()
    character = character.lower()
    
    # Variable to hold the count of character
    count_of_character = 0    
    
    # Iterating through the possible values of i, where i is the starting index of each substring which is of the same length as the substring entered.    
    for i in range(len(source_string) - len(character) + 1):
       
        # Checking if each possible substring of the correct length is equivalent to the substring entered. If so, I increment my count by 1.
     if source_string[i: i + len(character)] == character:
            count_of_character += 1    
 
    return count_of_character
 
 
# Enter the string in which we need to search
sentence = input("Enter a string\n")
 
# Enter a string/character which needs to be searchedsub_string = input("Enter the substring to search\n")
 
# Print the count
print('Count of ' + sub_string + ' in ' + sentence + ' is ' + str(character_count(sentence, sub_string)))
The output of this program will be -
>> Enter a string
Help is always given at Hogwarts to those who ask for it
>> Enter the substring to search
h
>> Count of h in Help is always given at Hogwarts to those who ask for it is 4

Conclusion

In this post, we discussed how to calculate the number of occurrences of a character in a given string.

I would love to hear your thoughts on this post and would like to have suggestions from you to make this post better. 

Feel free to befriend me on Facebook, Twitter or Linked In or say Hi by email.

Comments

Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
making connectionscachingretrying failed requeststhreadingresponse parsingerror handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object…

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user.

The output of this UI will be like this -
I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started.
Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml fileNavigate to app\src\main\res\values\styles.xmlChange the style value from DarkActionBar to NoActionBar as below<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark&qu…