Count Characters in a Python String with count()
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
The str.count() method counts non-overlapping occurrences of a substring inside a Python string. Call it as text.count(sub), where text is the string, sub is the character or substring to find, and the return value is an integer. Optional start and end arguments restrict the search to text[start:end] without changing the original string. For example, 'banana'.count('a') returns 3, while 'banana'.count('na') returns 2. 'banana'.count('a', 2) scans from index 2 and returns 2; 'banana'.count('a', 2, 5) scans 'nan' and returns 1. The method is case-sensitive, so 'A' and 'a' are different. It also counts substrings, not just single characters. If the substring is absent, it returns 0. The original string is never modified. Unlike len(), which returns the total string length, count() targets a specific character or substring and reports only its frequency. Time complexity is O(n) for counting a single character across n scanned characters; for a substring of length m, worst-case matching can be O(n*m), although Python's optimized search is usually much faster. Space complexity is O(1). It is a built-in, readable alternative to a manual loop for simple counting tasks. Use count() when you need a quick frequency check for a character or pattern in a string. For multiple character frequencies, consider collections.Counter.