Print a list to a string?

M

mrstephengross

I would like to get the results of a print operation placed in a
string. For instance, you can very easily create a list and print it
to stdout:

x = [1,2,3]
print x # Will print [1,2,3]

What if I want the text "[1,2,3]" placed in a string? For instance,
something like:

x = [1,2,3]
str = ''
print str x # x = '[1,2,3]'

Any ideas?

Thanks,
--Steve
 
G

Gary Herron

mrstephengross said:
I would like to get the results of a print operation placed in a
string. For instance, you can very easily create a list and print it
to stdout:

x = [1,2,3]
print x # Will print [1,2,3]

What if I want the text "[1,2,3]" placed in a string? For instance,
something like:

x = [1,2,3]
str = ''
print str x # x = '[1,2,3]'

Any ideas?

Thanks,
--Steve
Use str(any-object) or repr(any_object) to turn an object into a string
representation of that object. Use str for a human friendlier
representation, and repr for a more explicit representation.

Gary Herron
 
B

Bruno Desthuilliers

mrstephengross a écrit :
I would like to get the results of a print operation

print is a statement, it doesn't yield any 'result'.
placed in a
string. For instance, you can very easily create a list and print it
to stdout:

x = [1,2,3]
print x # Will print [1,2,3]

What if I want the text "[1,2,3]" placed in a string? For instance,
something like:

x = [1,2,3]
str = ''

You're shadowing the builtin str type here.
print str x # x = '[1,2,3]'
>
Any ideas?

any of the following should do:

s = "%s" % x
s = repr(x)
 
S

Steven D'Aprano

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.)
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top