Python get position of string and the next X lines

Viewed 159

There's a lot of questions like this but they're all dealing with files. I'm just dealing with a string:

"""
Your username is: 
joe
normal
"""

I need to find the position of "Your username is: " and then grab the next 2 lines after it. There isn't a file.txt to work with.

2 Answers

You could split the text by Your username is: and than detect where Your username is: and than get the next to lines here's a code example

splittext = "Your username is: joe normal".split("Your username is:")
splittext.remove('')
for i in range(0, len(splittext)):
    splittext[i] = splittext[i][1:len(splittext[i])]

#returns joe normal

EDIT Ver 2:

Updated the code to reflect the new changes done to the input data

example ='''This is an example string
That has multiple lines
With the words Your username is:
joe
normal
It should NOT grab this line
However it should detect the next line as it has
Your username is:
jane
also_normal
Do not grab this line'''
grab = False
line_count = 0
for line in example.split('\n'):
    if grab == True and line_count < 2:
        print (line)
        line_count +=1
    elif 'Your username is:' in line:
        grab = True
        line_count = 0
    else:
        grab = False
        line_count = 0

The output of this will be:

joe
normal
jane
also_normal

EDIT Ver 1:

I think you are looking for a code that can process multi line string variable and present you with an answer.

example ='''This is an example string
That has multiple lines
With the words Your username is: joe normal in the string
Program should grab this first line
And this second line and print
It should NOT grab this line
However it should detect the next line as it has
Your username is: joe normal
Grab this first line again
And grab this second line as well
Do not grab this line'''

grab = False
line_count = 0
for line in example.split('\n'):
    if grab == True and line_count < 2:
        print (line)
        line_count +=1
    elif 'Your username is: joe normal' in line:
        grab = True
        line_count = 0
    else:
        grab = False
        line_count = 0

The output of this will be:

Program should grab this first line
And this second line and print
Grab this first line again
And grab this second line as well
Related