0

I am at the very first part of pset6, which is just loading words in the text files into memory. I am using a python dict structure. To test a simple case first, I created a test-words.txt file, put in some comments (same format as in the pset's text files) and several words. Then I wrote a short script:

dict_test = {}
with open("test-words.txt",'r') as ftest:
    for line in ftest:
        word_test = line.strip('\n')
        if (';' in word_test)==False:
            dict_test.update({word_test[0]:word_test})
print(dict_test)

which gives me this error:

dict_test.update({word_test[0]:word_test})

IndexError: string index out of range

I played around with the index of word_test. I believe it is really a string, so I couldn't figure out why I could not refer to index 0 directly. Even refering to word_test[1] gives the same error. For instance, this code would work:

i = 0
with open("test-words.txt",'r') as ftest:
for line in ftest:
    word_test = line.strip('\n')
    if (';' in word_test)==False:
        for i in range(len(word_test)):
            print(word_test[i])

It would print out each character of a word read. So I'm wondering what's wrong with my approach. Many thanks

1

Maybe you have a string that's empty, so has no character at index 0. There's no string terminator like in C that you could access.

| improve this answer | |
  • Good guess, as soon as I remove a blank line in my text file, the code works. But it looks like I'm not using a very good approach for this. The actual text files have blank lines too, and I need to find a way to bypass those lines – buitri84 Dec 5 '17 at 14:41
  • 1
    I put some check in there, like if len(line.strip()) and not line.strip().startswith(";"): – Blauelf Dec 5 '17 at 15:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .