i = iter(lambda: stringio.read(1),'Z') buf = ''.join(i) + 'Z'
Here iter used in this mode: iter(callable, sentinel) -> iterator .
''.join(...) pretty effective. The last operation of adding 'Z' ''.join(i) + 'Z' not so good. But it can be solved by adding 'Z' to the iterator:
from itertools import chain, repeat stringio = StringIO.StringIO('ABCZ123') i = iter(lambda: stringio.read(1),'Z') i = chain(i,repeat('Z',1)) buf = ''.join(i)
Another way to do this is to use a generator:
def take_until_included(stringio): while True: s = stringio.read(1) yield s if s=='Z': return i = take_until_included(stringio) buf = ''.join(i)
I conducted several performance tests. The performance of the methods described is approximately the same:
http://ideone.com/dQGe5
source share