i = iter(lambda: stringio.read(1),'Z')
buf = ''.join(i) + 'Z'
Here iter
is used in this mode: iter(callable, sentinel) -> iterator
.
''.join(...)
is quite effective. The last operation of adding 'Z' ''.join(i) + 'Z'
is not that good. But it can be addressed 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)
One more way to do it is to use 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 made some efficiency tests. The performance of the described techniques is pretty the same:
http://ideone.com/dQGe5
datalist
object. It's possible to rewrite this code with generator instead of function (join
accepts iterators), so there will be no temporary redundant objects in memory. – Baalbek