Print a list to a string?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Oct 31 18:38:40 EDT 2007


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)





More information about the Python-list mailing list