printing a sequence...

Lonnie Princehouse finite.automaton at gmail.com
Fri Jul 16 19:53:44 CEST 2004


To clarify what's already been said-

   thing.__str__() is equivalent to str(thing)

   thing.__repr__() is equivalent to repr(thing)


str(some_list) will call repr() for all of the list's items.

You could try:

   print map(str, a)   

or
    
   print [str(x) for x in a]

for the desired effect, or you could overload __repr__ instead of __str__


"Florian Preknya" <bolo at coco.ro> wrote in message news:<cd8a1u$t6d$1 at nebula.dnttm.ro>...
> Hi everybody,
> 
> I'm relatively new in using Python and I want to perform a simple job: I
> have a list of objects of type A and want to print them to stdout.
> 
> class A:
>     def __init__(self, value):
>         self.value = value
> 
>     def __str__(self):
>         return "value: %d" % self.value
> 
> a = [A(10), A(12), A(2)]
> print str(a)
> 
> I obtain [<__main__.A instance at 0x00767D80>, <__main__.A instance at
> 0x00768698>, <__main__.A instance at 0x00768350>].
> What I want to obtain is [value: 10, value: 12, value: 2].
> 
> I know that if I change the __str__ to __repr__ I obtain what I want, but
> then I will have these informal strings in debuger also, and I do not want
> that.
> 
> Can I write somehow the print statement to force calling the A.__str__
> function?
> 
> Thanks,
> Florian.



More information about the Python-list mailing list