Friday 21 August 2020

Counting number of occurrences of each character in a string


Using count() method:

string_data=input("Enter string: ")
l=[]
for x in string_data:
	if x not in l:
		l.append(x)
		print(x,"occurred",string_data.count(x),"times")

Without using count() method:

string_data=input("Enter string: ")
d={}
for x in string_data:
	d[x]=d.get(x,0) + 1
print(d)
print(d.items())
# for meaningful output
for key,value in sorted(d.items()):
	print(key,"occurred",value,"times")  

 

Question by Subscriber: 

 How to ignore special characters like ? , . etc

If you want to ignore special characters and focus on the alphabets and digits only, then you can do that by some extra work

You  can either import string class to get a set of all characters that you need to focus on, or you can manually add the set of characters you particularly want to focus on.

we will name them as valid_characters
Here goes the code:

import string
string_data=input("Enter string: ")
l=[]
valid_characters=set(string.ascii_letters+string.digits)
for x in string_data:
	if x in valid_characters:
		if x not in l:
			l.append(x)
			print(x,"occurred",string_data.count(x),"times")

Output: 

or

string_data=input("Enter string: ")
l=[]
valid_characters=set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+'0123456789')
for x in string_data:
	if x in valid_characters:
		if x not in l:
			l.append(x)
			print(x,"occurred",string_data.count(x),"times")



Hope you like it ..!

No comments:

Post a Comment