Print a list to a string?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Oct 31 18:39:37 EDT 2007


On Wed, 31 Oct 2007 22:17:48 +0000, mrstephengross wrote:

> I would like to get the results of a print operation placed in a string.

s = str(x)


If you specifically need to capture the output of print, then something 
like this:


>>> import cStringIO
>>> s = cStringIO.StringIO()
>>> print >>s, [1, 2, 1.0/5, 'hello world']
>>> s.getvalue()
"[1, 2, 0.20000000000000001, 'hello world']\n"


(And please, please, PLEASE don't ask why 1/5 is 0.2000...01 until you've 
read the FAQs on the Python website. Thank you.)



-- 
Steven



More information about the Python-list mailing list