Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count occurrences of a character in string in Python
We are given a string and a character, and we want to find out how many times the given character is repeated in the string. Python provides several approaches to count character occurrences.
Using count() Method
The simplest approach is using Python's built-in count() method ?
text = "How do you do"
char = 'o'
print("Given String:", text)
print("Given Character:", char)
print("Number of occurrences:", text.count(char))
Given String: How do you do Given Character: o Number of occurrences: 4
Using range() and len()
We can design a for loop to match the character with every character present in the string using index-based access ?
text = "How do you do"
char = 'o'
print("Given String:", text)
print("Given Character:", char)
count = 0
for i in range(len(text)):
if text[i] == char:
count = count + 1
print("Number of occurrences:", count)
Given String: How do you do Given Character: o Number of occurrences: 4
Using Counter from collections
We can use the Counter function from the collections module to get the count of each character in the string ?
from collections import Counter
text = "How do you do"
char = 'o'
print("Given String:", text)
print("Given Character:", char)
count = Counter(text)
print("Number of occurrences:", count[char])
Given String: How do you do Given Character: o Number of occurrences: 4
Using List Comprehension
A concise approach using list comprehension with sum() ?
text = "How do you do"
char = 'o'
print("Given String:", text)
print("Given Character:", char)
count = sum(1 for c in text if c == char)
print("Number of occurrences:", count)
Given String: How do you do Given Character: o Number of occurrences: 4
Comparison
| Method | Complexity | Best For |
|---|---|---|
count() |
O(n) | Simple character counting |
range() + len() |
O(n) | Learning purposes |
Counter |
O(n) | Multiple character counts |
| List comprehension | O(n) | Functional programming style |
Conclusion
Use count() for simple character counting as it's the most readable and efficient. Use Counter when you need counts for multiple characters simultaneously.
Advertisements
