Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply __str__ function when printing a list of objects in Python

Well this interactive python console snippet will tell everything:

>>> class Test: ...     def __str__(self): ...         return 'asd' ... >>> t = Test() >>> print(t) asd >>> l = [Test(), Test(), Test()] >>> print(l) [__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,  __main__.Test instance at 0x00CBC238] 

Basically I would like to get three asd string printed when I print the list. I have also tried pprint but it gives the same results.

like image 662
dvim Avatar asked Aug 24 '10 16:08

dvim


People also ask

How do you print a list of items in a string in Python?

Convert a list to a string for display : If it is a list of strings we can simply join them using join() function, but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.

What does __ str __ function do in Python?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

Does str () work on lists?

The str() function in python is used to turn a value into a string. The simple answer to what the str() does to a list is that it creates a string representation of the list (square brackets and all).


1 Answers

Try:

class Test:    def __repr__(self):        return 'asd' 

And read this documentation link:

like image 112
gruszczy Avatar answered Sep 20 '22 20:09

gruszczy