Frankenstring
Peter Otten
__peter__ at web.de
Wed Jul 13 04:11:35 EDT 2005
Thomas Lotze wrote:
> I think I need an iterator over a string of characters pulling them out
> one by one, like a usual iterator over a str does. At the same time the
> thing should allow seeking and telling like a file-like object:
>>> from StringIO import StringIO
>>> class frankenstring(StringIO):
... def next(self):
... c = self.read(1)
... if not c:
... raise StopIteration
... return c
...
>>> f = frankenfile("0123456789")
>>> for c in f:
... print c
... if c == "2":
... break
...
0
1
2
>>> f.tell()
3
>>> f.seek(7)
>>> for c in f:
... print c
...
7
8
9
>>>
A non-intrusive alternative:
>>> def chariter(instream):
... def char(): return instream.read(1)
... return iter(char, "")
...
>>> f = StringIO("0123456789")
>>> for c in chariter(f):
... print c
... if c == "2": break
...
0
1
2
>>> f.tell()
3
Performance is probably not so good, but if you really want to do it in C,
with cStringIO you might be /almost/ there.
Peter
More information about the Python-list
mailing list