Python String count
Now, we are going to learn about the count method in relation to the string. As the name says, the count method is going to help us count the number of times some string occurs in the specified string. For example, if we were to count how many times ‘a’ occurs in the string ‘Gyanipandit’, then the answer would be simply 2. So, Let’s have a look at an example over here.
Python String count() Method
In the above example, you can simply see that we are calling the count method on the string, to count how many times ‘a’ has occurred in the string. This method returns the count. The output to this program would be 2. we have directly printed the return value, but you can also assign that return value to some variable, as per the requirement.
Also, you can count for some bigger strings as well. Have a look at the below example –
As you can see, in the above program, we have a comparatively bigger string, and we are looking for how many times has python occurred in the string. The answer is again 2.
Now, Let’s say that we pass such a string as an argument to the count method, which is not there in the string. In such a situation, the return value from the count method is going to be 0. Let’s have a look at another program, which tries to demonstrate the same thing.
As you can see in the above program, we have a string, and then we are using the count method on the string. We are trying to count, how many times the string ‘python’ occurred in the string1. We know that the string ‘python’ is not present in the string at all, so the count method would return 0.
You can try executing the program and observing the output.
So, you can use the count method, whenever you require to count how many times some string has occurred.