Python Forum

Full Version: Extracting elements in a list to form a message using for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I'm trying to make a function that will extract letters from a text document to reveal a secret message. I'm stuck at the at the for loop. It says "list object cannot be interpreted as an integer".
def decodefile():
        fr = open("sentences.txt")
        line = fr.readline()    
        
        codeKey = [[0, 1, 2, 4, 7, 14], [6], [1, 16], [7,8], [14,18]]
        while (line) :
            listLine = [ch for ch in line] 
            for x in range(0, len(listLine), codeKey):
                print(codeKey)

            line = fr.readline()
            
        fr.close
decodefile()
Here is the text if it matters.

They like apples.
I enjoy pears.
Time for breakfast.
Serve the oatmeal please.
Leave a tip for the waiter.
1) You didn't close your file. In order to easily avoid that sort of mistake, use a with-block:
with open("sentences.txt") as fr:
    for line in fr:
        # do something with the line
2) The third argument to range() is the step. So range(0, 10, 2) == [0, 2, 4, 6, 8]
codeKey is a list, not an int, so it doesn't make sense to be used there.
Each code key is associated with a particular line. For each line, you need to get the matching code key. You do this with for line, indexes in zip(fr, codeKey):.