Search code examples
pythonprogramming-languages

I am creating a python program that counts the number of characters input by user in a file that is not case-sensitive


I am having problem with my code and a TypeError: string indices must be integers, not str. Any help or suggestion?

my code is:

f= open("studentname.txt", 'r')
finChar = raw_input("please enter a character to count ")
a=finChar.lower()
b=finChar.upper()
c=a+b
str = ''
for line in f.readlines():
     str = str + line
count = 0
for i in str:
    if str[i]== c :
        count = count + 1
f.close()
print "the total character in the file is ", count

Solution

  • for i in str iterates over the characters in a string, not their indices. Therefore you can write

    for i in str:
        if i in c: