Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any push back like function in python?

Tags:

python

Sorry guys!!! pardon me. I'm a beginner in Python. I am writing the following code:

for line in file:
 if StartingMarker in line:
  # Here: I want to push back 'line' back in 'file'
    for nextline in file:
     if EndingMarker in line:
        # Do some Operation
print "Done"

How can I push 'line' back in 'file'?

Thanks in Advance.

like image 478
Humble Learner Avatar asked Nov 14 '10 03:11

Humble Learner


People also ask

What is the difference between push () and pop () function in Python?

push () function is used to grow context stack and pop () is another function and used to restore stack to previous push. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

How many Push functions are there in context Stack in Python?

There are total four push functions for context stack. push () function is used to grow context stack and pop () is another function and used to restore stack to previous push. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

How does any () work in Python?

Fortunately, any () in Python is such a tool. It looks through the elements in an iterable and returns a single value indicating whether any element is true in a Boolean context, or truthy. Let’s dive right in!

Can a function return a result in Python?

A function can return data as a result. In Python a function is defined using the def keyword: To call a function, use the function name followed by parenthesis: Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses.


1 Answers

Don't push back, yield.

def starttoend(it):
  for line in it:
    if 'START' in line:
      yield line
      break
  for line in it:
    yield line
    if 'END' in line:
      break

l = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb']

i = iter(l)
for line in starttoend(i):
  print line

Just use the iterator again if you need more sequences.

like image 161
Ignacio Vazquez-Abrams Avatar answered Sep 16 '22 17:09

Ignacio Vazquez-Abrams