Convert StringIO to string

paul paul at subsignal.org
Mon Oct 16 15:21:11 CEST 2006


Jonathan Bowlas schrieb:
> Hi listers,
> 
> I've written this little script to generate some html but I cannot get it to
> convert to a string so I can perform a replace() on the >, <
> characters that get returned.
> 
> from StringIO import StringIO
> 
> def generator_file(rsspath,titleintro,tickeropt): 
> 	scripter=StringIO()
> 	scripter.write('<script type="text/javascript">\n')
> 	scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath,
> titleintro, tickeropt))
> 	scripter.write('</script>\n')
> 	return scripter.getvalue()
> 
> I tried adding this:
> 
> scripter = scripter.replace("<", "<")
> scripter = scripter.replace(">", ">")
I'm not sure why you are using a StringIO instance here, but the
standard library has all you need:

from StringIO import StringIO
from xml.sax.saxutils import escape, unescape

def generator_file(rsspath, titleintro, tickeropts):
  #unescape your strings first
  rsspath, titleintro, tickeropts = map(unescape, [rsspath, titleintro,
tickeropts])
  scripter=StringIO()
  scripter.write('<script type="text/javascript">\n')
  scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, titleintro,
tickeropt))
  scripter.write('</script>\n')
  return scripter.getvalue()

I'm still curious what all this StringIO stuff is for ;)

cheers
 Paul






More information about the Python-list mailing list