1

I have a multi-line variable called text that I'm iterating over, line by line. First I need to look for a matching regex, then do some operations on the very following line. So I was wondering if there was a neat/pythonic way to do this - the only thing I could think of was adding a boolean variable to keep track of whether or not the previous line contained the regex.

0

1 Answer 1

4

One pythonic way to iterate over adjacent pairs of elements uses zip with a 1-offset slice:

lines = text.split("\n")

for line1, line2 in zip(lines, lines[1:]):
    if whatever(line1):
        do_horrible_things(line2)

Here, line2 would be an immutable string, so if you needed any changes to be reflected in lines, you would have to use indeces (as produced here by enumerate):

for i, line in enumerate(lines):
    if whatever(line):
        lines[i+1] = do_horrible_things(lines[i+1]) 
        # and safeguard against line being the last one
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.