Search code examples
python-3.xtypeerrortext-filesfile-handling

TypeError: string indices must be integers --> Python


I wanted to create a python function which should read each character of a text file and then count and display the occurrence of alphabets E and T individually (including small cases e and t too).

def test():
    f = open("poem.txt",'r')
    count = 0
    count1 =0
    try:
        line = f.readlines()
        for i in line:
            for x in line:
                if (i[x] in 'Ee'):
                    count+=1
                else:
                    if (i[x] in 'Tt'):
                        count1+=1
        print("E or e",count)
        print("T or t",count1)
    except EOFError:
        f.close()
test()

This is what I tried

And it gave :

File "/Users/ansusinha/Desktop/Tution/Untitled15.py", line 23, in test
    if (i[x] in 'Ee'):
TypeError: string indices must be integers

What am I missing here?


Solution

  • Because, f.readlines() does not read only line, it reads all lines. Code should be like this

    def test():
        f = open("poem.txt",'r')
        count = 0
        count1 =0
        try:
            lines = f.readlines()
            for line in lines:
                for char_in_line in line:
                    if (char_in_line in 'Ee'):
                        count+=1
                    elif (char_in_line in 'Tt'):
                        count1+=1
            print("E or e",count)
            print("T or t",count1)
        except EOFError:
            f.close()
    test()
    

    If your poem.txt is this,

    LaLaLa
    I'm shoes.
    Who are you?
    

    Then i[x] should be like this i["LaLaLa"]