easy string formating question
Simon Forman
rogue_pedro at yahoo.com
Thu Aug 10 20:28:59 EDT 2006
Slawomir Nowaczyk wrote:
> On Thu, 10 Aug 2006 11:39:41 -0700
> f pemberton <fpemberton133 at yahoo.com> wrote:
>
> #> I have kind of an interesting string, it looks like a couple hundred
> #> letters bunched together with no spaces. Anyway, i'm trying to put a
> #> "?" and a (\n) newline after every 100th character of the string and
> #> then write that string to a file. How would I go about doing that? Any
> #> help would be much appreciated.
>
> In addition to all the other ideas, you can try using StringIO
>
> import StringIO
> s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
> size = 10 # 100
> input = StringIO.StringIO(s)
> while input.tell()<input.len: # is there really no better way to check for exhausted StringIO ?
> print input.read(size)+"?\n",
> # instead of print just write to a file or accumulate the result
>
>
> --
> Best wishes,
> Slawomir Nowaczyk
> ( Slawomir.Nowaczyk at cs.lth.se )
>
> "Reality is that which, when you stop believing in it,
> doesn't go away." -- Philip K. Dick
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):
import StringIO
s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
size = 10 # 100
S = StringIO.StringIO(s)
data = S.read(size)
while data:
print data + "?\n",
data = S.read(size)
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()
More information about the Python-list
mailing list