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.
Add a comment
|
1 Answer
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