Print a list to a string?

Gary Herron gherron at islandtraining.com
Wed Oct 31 18:34:05 EDT 2007


mrstephengross wrote:
> 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




More information about the Python-list mailing list