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)?
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).
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.
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.
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.
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__()
You can use a list comprehension to generate a new list with each item str()'d automatically:
print([str(item) for item in mylist])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With