By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,768 Members | 2,004 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,768 IT Pros & Developers. It's quick & easy.

Convert StringIO to string

P: n/a
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
Oct 16 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jonathan Bowlas wrote:
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!"):
>>import StringIO
s = StringIO.StringIO()
s.write("hello world\n")
s.seek(0)
s.read()
'hello world\n'
>>s = StringIO.StringIO()
s.write("hello world\n")
s.read()
''

Oct 16 '06 #2

P: n/a
Jonathan Bowlas wrote in
news:ma**************************************@pyth on.org 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.
--
http://www.victim-prime.dsl.pipex.com/
Oct 16 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.