Python Forum
Extracting elements in a list to form a message using for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extracting elements in a list to form a message using for loop
#1
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.
Reply
#2
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.
Reply
#3
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):.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help with adding duplicates elements together in a list 2ECC3O 5 2,053 Sep-10-2022, 07:11 AM
Last Post: 2ECC3O
  Unexpected behavior accessing list elements. tonyflute 2 2,273 Apr-09-2021, 02:36 PM
Last Post: tonyflute
  How to find difference between elements in a list? Using beginner Basics only. Anklebiter 8 4,363 Nov-19-2020, 07:43 PM
Last Post: Anklebiter
  Get 5 most unique combinations of elements in a 2D list wanttolearn 1 2,317 Sep-24-2020, 02:26 PM
Last Post: buran
  Extracting link list to json file naor 5 2,626 Sep-17-2020, 04:16 PM
Last Post: micseydel
  Loop through elements of list and include as value in the dictionary Rupini 3 2,658 Jun-13-2020, 05:43 AM
Last Post: buran
  How can I print the number of unique elements in a list? AnOddGirl 5 3,302 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  Sum of elements on the list recursive sev 3 2,570 Jun-20-2019, 02:14 PM
Last Post: sev
  Extracting list element with user input valve 1 2,587 Mar-11-2019, 07:37 PM
Last Post: Yoriz
  reach the elements in the list ptah 7 5,045 Oct-04-2017, 08:12 PM
Last Post: ptah

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020