Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __str__ and lists

Tags:

python

In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:

"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"

Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:

print 'my list is %s'%(list)

it looks something like this:

[<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>]

how can I get python to call my __str__() automatically for each element inside the list (or dict for that matter)?

like image 243
benhsu Avatar asked Oct 11 '22 11:10

benhsu


People also ask

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

What does __ str __ mean in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

Can you print a string with a list 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.

Can Python have a list of objects?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.


2 Answers

Calling string on a python list calls the __repr__ method on each element inside. For some items, __str__ and __repr__ are the same. If you want that behavior, do:

def __str__(self):
    ...
def __repr__(self):
    return self.__str__()
like image 164
David Berger Avatar answered Oct 19 '22 07:10

David Berger


You can use a list comprehension to generate a new list with each item str()'d automatically:

print([str(item) for item in mylist])
like image 27
Dan Lew Avatar answered Oct 19 '22 07:10

Dan Lew