Home > database >  TypeError: string indices must be integers --> Python
TypeError: string indices must be integers --> Python

Time:11-02

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?

CodePudding user response:

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"]

CodePudding user response:

You are missing the fact that Python strings come with a .count() method.

You can read the entire file with

file_as_string = f.read()

and then count occurrences of any substring with

amount_of_E = file_as_string.count('E')

Check out str.count in Python documentation.

With

amount_of_Ee = file_as_string.lower().count('e')

you count occurrences of both E and e and with

amount_of_Tt = file_as_string.lower().count('t')

you are done with counting using two lines of code.


In your own code you try to index a string with another string, but string indices must be integers.

With for x in line: you actually wanted for x in i: where then the x will be a single character of line i you could directly use in if x in 'eE':.

But there is no need for the loops at all as Python strings come with the .count() method, so just use it.

  • Related