The task of count the occurrences of a character in string in Python is to be given. This operation is useful for many purposes, such as removing duplicates and detecting unwanted characters.
Iterate the entire string for that particular character and then increase the counter when we encounter the particular character.
test_str = "Welcome you to ittutoria"
count = 0
for i in test_str:
if i == 'o':
count = count + 1
print ("Count of o in 'Welcome you to ittutoria' is : + str(count))
Output :
Count of o in 'Welcome you to ittutoria' is : 4
count(), which is the most common method to find the presence of any element within any container in Python, is the best. This method is simple to code and easy to remember, making it very popular.
test_str = "Welcome you to ittutoria"
counter = test_str.count('o')
print ("Count of o in 'Welcome you to ittutoria' is : " + str(counter))
Output :
Count of o in 'Welcome you to ittutoria' is : 4
This is the less well-known method of obtaining the occurrences of an element in any Python container. This performs the same task as above, but is a function from a different library, i.e. collections.
from collections import Counter
test_str = "Welcome you to ittutoria"
count = Counter(test_str)
print ("Count of o in 'Welcome you to ittutoria' is : " + str(count['o']))
Output :
Count of o in 'Welcome you to ittutoria' is : 4
Lambda functions can be used in conjunction with sum() and map() to accomplish the task of counting all instances of a particular element within a string. To sum up all map() occurrences, this uses sum().
test_str = "Welcome you to ittutoria"
count = sum(map(lambda x : 1 if 'o' in x else 0, test_str))
print ("Count of o in 'Welcome you to ittutoria' is : " + str(count))
Output :
Count of o in 'Welcome you to ittutoria' is : 4
Regular expressions are useful for many string-related coding tasks. Regular Expressions can be used to assist us in finding an element in string.
import re
test_str = "Welcome you to ittutoria"
count = len(re.findall("o", test_str))
print ("Count of o in 'Welcome you to ittutoria' is : " + str(count))
Output :
Count of o in 'Welcome you to ittutoria' is : 4
Follow detailed instructions on methods at https://ittutoria.net/count-occurrences-of-a-character-in-a-string-in-python/