Search code examples
pythonstringline

Reading specific line from string


I'm trying to read the content of specific lines in a string stored as a variable. However I only know how to find it if it looks through a file, which would be like this:

line = dayresult.readlines()
print line[3]

The string I'm looking for is taken from a file, but I only know the content's position in the string, but not in the file itself, due to how large it is, and it will change each day.

So if anyone knows how to store the content on a specific line in the string as a variable that would be great.

EDIT: I'm trying to get a certain line in a string that is currently being stored as a variable. I need the content on specific line numbers, and only those.


Solution

  • I don't think I understand what you're trying to do. "readlines" gives you a list of strings/lines. So now you got the whole file as a list of lines. But as far as I understand, you only know the position of the information you want in a line, but you don't know what line you're looking for?

    I think you're looking for:

    with open(filename, "r") as file_variable:
           for line in file_variable:
                 #look for your content in each line
    

    Edit: The answer is:

    import re
    ....
    re.split("\n", file_variable)