Search code examples
pythonlistindexingnon-alphanumeric

Get the index of a non-alphanumeric-string in a list containing non-alphanumeric elements in python


I have a file (test.txt) like this:

[06/Oct/2017:20:18:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18
[06/Oct/2017:20:19:59 +0200] [pool-2-thread-7] ends.
[06/Oct/2017:20:20:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:21:24 +0200] [pool-2-thread-4] ends.
[06/Oct/2017:20:21:34 +0200] [pool-2-thread-8] ends.

As a python-beginner i wanted to get the linenumber of a specific line, so i searched for a solution and found this post: Finding the index of an item given a list containing it in Python. I am using the answer of @tanzil, because later on it is possible, that i do look for elements not in the list.

This is what i do:

Save the lines of the original file in a list:

with open(test.txt) as f:
    content = [line.rstrip('\n') for line in f]
    print len(content)
index = [x for x in range(len(content))]

Iterate through the original file:

with open(test.txt, "r") as file:
    for line in file:
        print find_element_in_list(index, line.rstrip('\n'))

Find the index of each line of the original file:

def find_element_in_list(index_list, list_element):
    try:
        index_element = index_list.index(list_element)
        return index_element
    except ValueError:
        return None

As a result, there is no match at all. I only get "None" as output.

I read this post 'is' operator behaves differently when comparing strings with spaces and hoped to get an answer to my question, but couldn't adapt the answers to my problem.

I would apreciate any hints or ideas!

(This is not a dublicate of Get Line Number of certain phrase in file Python because i need to access the indices of different lines multiple times. I am not iterating through the file everytime i need a specific one.)


Solution

  • I think you are looking in the wrong list. Instead of looking in the index, try looking in content

    with open('test.txt', "r") as file:
        for line in file:
            print find_element_in_list(content, line.rstrip('\n'))