Goutam Reddy Goutam Reddy - 18 days ago 6
Python Question

how to count repeated characters in text file using python

i am beginner in python and i am trying to make a small program in python to count repeated character in a text file

here is the code

import string

def count_char(text,char):
count = 0
for c in text:
if c == char:
count +=1
return count

filename = raw_input("Enter File name:")
with open(filename) as f:
text=f.read()

print(count_char(text,"r"))


but it prints output as

>> 0


please tell me what is the wrong with my code ?

Answer

Move your return to be outside of the for loop. It's currently only going through 1 iteration.

Comments