pythontypeerrorcoderunner

Why does my code give the TypeError: TypeError: 'int' object has no attribute '__getitem__'?


I am making a script on Python that you give a string, and it will find the count of the letters in the string, input it into a list, and add up that list. My script runner keeps giving this error:

Traceback (most recent call last):
File "Untitled.py", line 9, in <module>
countersplit = len(tosplit[counter])
TypeError: 'int' object has no attribute '__getitem__'

My code is as follows:

userin = raw_input("Enter sentence: ")
split = userin.split()
tosplit = len(split)
print(tosplit)
counter = 0
countersplit = 0
while counter < tosplit:
    countersplit = len(tosplit[counter])
    wordcount = [countersplit]
    print(wordcount)
    print(countersplit)
    counter = counter + 1

What can I do you fix this problem?


Solution

  • Maybe this is what you're trying to achieve.

    userin = raw_input("Enter sentence: ")
    split = userin.split()
    word_counts = list()
    total_letters = 0
    for i in split:
        word_count = len(split)
        print(word_count)
        word_counts.append(word_count)
        total_letters += word_count
    print(total_letters)