easy string formating question

Slawomir Nowaczyk slawomir.nowaczyk.847 at student.lu.se
Fri Aug 11 06:48:30 EDT 2006


On Thu, 10 Aug 2006 17:28:59 -0700
Simon Forman <rogue_pedro at yahoo.com> wrote:

#> There is a better way to check for exhausted StringIO (Note that
#> "input" is a python built-in and should not be used for a variable
#> name):

Right, thanks for pointing it out.

#> import StringIO
#> s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#> size = 10  # 100
#> S = StringIO.StringIO(s)
#> 
#> data = S.read(size)
#> while data:
#>     print data + "?\n",
#>     data = S.read(size)

It may be only my personal opinion, but duplicating data = S.read(size)
line doesn't strike me as particularly better.

#> However, it's considered more "pythonic" to do it like so (also uses a
#> StringIO as an output "file" to show how print can print to a file-like
#> object):
#> 
#> import StringIO
#> 
#> s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#> size = 10  # 100
#> 
#> S = StringIO.StringIO(s)
#> out = StringIO.StringIO()# stand-in for a real file.
#> 
#> while True:
#>     data = S.read(size)
#>     if not data:
#>         break
#>     print >> out, data + "?\n",
#>    
#> print out.getvalue()

This looks slightly nicer, but still, I wish there was some kind of
StringIO.isEOF() to put in while condition.

Don't take me wrong, I love "while True" stuff, but sometimes having
an actual test there can be nice :)

-- 
 Best wishes,
   Slawomir Nowaczyk
     ( Slawomir.Nowaczyk at cs.lth.se )

Beware of bugs in the above code; I have only proved it correct,
not tried it.




More information about the Python-list mailing list