Sometimes, we want to count the number of occurrences of a character in a string with Python.
In this article, we’ll look at how to count the number of occurrences of a character in a string with Python.
How to count the number of occurrences of a character in a string with Python?
To count the number of occurrences of a character in a string with Python, we can use the string count
method.
For instance, we write
c = 'Mary had a little lamb'.count('a')
to count the number of occurrences of 'a'
in the 'Mary had a little lamb'
string.
Conclusion
To count the number of occurrences of a character in a string with Python, we can use the string count
method.