Re: Frankenstring
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Frankenstring

From: Peter Otten <__peter__@web.de>
Date: Wed Jul 13 2005 - 10:11:35 CEST

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
Received on Thu Sep 29 16:55:24 2005