Convert StringIO to string

J

Jonathan Bowlas

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("&lt;", "<")
scripter = scripter.replace("&gt;", ">")

But obviously replace() isn't an attribute of StringIO so I guess I need to
convert it to a string first, can someone please advise how I can do this?

Cheers

Jon
 
S

skryskalla

Jonathan said:
But obviously replace() isn't an attribute of StringIO so I guess I need to
convert it to a string first, can someone please advise how I can do this?

StringIO objects are file-like objects, so you need to use read or
readlines to get the string data out of it (just like a regular file).
Before reading remember to seek back to the beginning to get all of the
data ("Be kind, rewind!"):
'hello world\n'
''
 
R

Rob Williscroft

Jonathan Bowlas wrote in
in
comp.lang.python:
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 &gt;,
&lt; 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("&lt;", "<")
scripter = scripter.replace("&gt;", ">")

But obviously replace() isn't an attribute of StringIO so I guess I
need to convert it to a string first, can someone please advise how I
can do this?

How strange, you are already "converting" to a string in the return
line (the call to the getvalue() method), so:

scripter = scripter.getvalue().replace("&lt;", "<")
scripter = scripter.replace("&gt;", ">")
return scripter

should do what you want.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top