All IT Courses 50% Off
Python Tutorials

Python Count Method for Strings

You may get into situations you will be required to count the occurrence of a particular element in a string. Python allows you to do this easily with the count() method. The count() method in Python simply returns the total number of times a specified element occurs in a string. You can also tweak the index you want the Python interpreter to begin its search. In this tutorial, you will learn how to use the count method in Python. Specifically, by the end of the tutorial, you will know the following. 

  • Syntax of the count() method.
  • Defining the start and end parameter
  • Counting Substrings in a String

We’d begin with its syntax. 

Syntax of the count() method.

Docstring:
S.count(sub[, start[, end]]) -> int
 
Return the number of non-overlapping occurrences of substring sub in
string S[start:end].  Optional arguments start, and end are
interpreted as in slice notation.
Type:      builtin_function_or_method

As seen from the docstring, the method takes three parameters (2 are optional): the sub, start, and end. 

  • sub: This is the substring or character you wish to count. It is a required argument to pass when calling the count() method. Failure to pass this first argument would throw an error. On the other hand, when the substring character is given, the method counts the number of times it occurs and returns that count. 
  • start: This is an optional parameter. By default, Python begins its search from the index of the string in python. If you wish to change where the search starts, you can define the index with the start parameter. 
  • end: This is an optional parameter. This is the counterpart of the start parameter. If you do not want the entire string to be searched, you can define the end parameter, which would indicate the index where the search should stop. Note that without defining this parameter, the search and count are done until the string’s end. 

Returns:

As earlier explained, the count() method returns an integer of the number of times a character or substring occurs. If the character or substring is not found, the count() method returns 0.

All IT Courses 50% Off

Now let’s take some examples.

#define some string
string = "I am learning Python with H2k Infosys."
 
#count the occurence of i in the string
string_count = string.count('i')  
print(f"The letter i occurs {string_count} times in the string")
Output:
The letter i occurs 2 times in the string

Notice that the ‘i’ in the upper case was not counted. One way to go about this is to convert all the letters to uppercase and then count the uppercase i. See the code below.

string = "I am learning Python with H2k Infosys."
 
#count the occurence of i in the string
string_in_uppercase = string.upper()
string_count = string_in_uppercase.count('I')  
print(f"The letter i occurs {string_count} times in the string")
Output:
The letter i occurs 4 times in the string

Now the code counts letter I in uppercase. 

Defining the start and end parameter

Now, let us see an example where the start and end arguments are defined. Let’s print the index for each index before going forward.

#define some string
string = "I am learning Python with H2k Infosys."
 
#count the occurence of i in the string
string_in_uppercase = string.upper()
string_count = string_in_uppercase.count('I', 3, 20) 
 
#print the index of each element
for i, j in enumerate(string):
    print(j, 'is on index', i)
print(f"The letter i occurs {string_count} times in the string")
Output:
I is on index 0
  is on index 1
a is on index 2
m is on index 3
  is on index 4
l is on index 5
e is on index 6
a is on index 7
r is on index 8
n is on index 9
i is on index 10
n is on index 11
g is on index 12
  is on index 13
P is on index 14
y is on index 15
t is on index 16
h is on index 17
o is on index 18
n is on index 19
  is on index 20
w is on index 21
i is on index 22
t is on index 23
h is on index 24
  is on index 25
H is on index 26
2 is on index 27
k is on index 28
  is on index 29
I is on index 30
n is on index 31
f is on index 32
o is on index 33
s is on index 34
y is on index 35
s is on index 36

Now, let’s say we want the count to begin at the 3rd index and end at the 15th index.

#define some string
string = "I am learning Python with H2k Infosys."
 
#count the occurence of i in the string
string_in_uppercase = string.upper()
string_count = string_in_uppercase.count('I', 3, 20) 
 
 
print(f"The letter i occurs {string_count} times in the string")
Output:
The letter i occurs 1 times in the string

As seen, it is only the letter between index 3 and 20 that was counted. 

Counting Substrings in a String

Substrings are strings in a string. You can also count the occurrence of substrings in a string. You only need to pass the substring you wish to count as an python argument to the count() method. In the example below, we will count the number of times the word ‘H2k’ occurs in the string.

string = '''I am learning Python with H2k Infosys.
            I knew about H2k from a friend who took one of their courses and now works in a Big Fintech company. 
            The classes in H2k are easy to follow and project-oriented. 
            I learned many hands-on skills from their experienced instructors. 
            I recommend H2k to anyone that wishes to learn Digital Skills.
'''
#count the occurence of H2k in the string
string_count = string.count('H2k')  
print(f"The substring H2k occurs {string_count} times in the string")
Output:
The substring H2k occurs 4 times in the string.

And that’s how to work with the count() method. If you have any questions, please leave them in the comment section, and I’d do my best to answer them.

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Check Also
Close
Back to top button