Reputation: 5526
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)?
Upvotes: 147
Views: 122414
Reputation: 46341
This should suffice.
When printing lists as well as other container classes, the contained elements will be printed using __repr__
, because __repr__
is meant to be used for internal object representation.
If we call: help(object.__repr__)
it will tell us:
Help on wrapper_descriptor:
__repr__(self, /)
Return repr(self).
And if we call help(repr)
it will output:
Help on built-in function repr in module builtins:
repr(obj, /)
Return the canonical string representation of the object.
For many object types, including most builtins, eval(repr(obj)) == obj.
If __str__
is implemented for an object and __repr__
is not repr(obj)
will output the default output, just like print(obj)
when non of these are implemented.
So the only way is to implement __repr__
for your class. One possible way to do that is this:
class C:
def __str__(self):
return str(f"{self.__class__.__name__} class str ")
C.__repr__=C.__str__
ci = C()
print(ci) #C class str
print(str(ci)) #C class str
print(repr(ci)) #C class str
Upvotes: 1
Reputation: 21
The output you're getting is just the object's module name, class name, and then the memory address in hexadecimal as the the __repr__
function is not overridden.
__str__
is used for the string representation of an object when using print. But since you are printing a list of objects, and not iterating over the list to call the str
method for each item it prints out the objects representation.
To have the __str__
function invoked you'd need to do something like this:
'my list is %s' % [str(x) for x in myList]
If you override the __repr__
function you can use the print method like you were before:
class cell:
def __init__(self, id):
self.id = id
def __str__(self):
return str(self.id) # Or whatever
def __repr__(self):
return str(self) # function invoked when you try and print the whole list.
myList = [cell(1), cell(2), cell(3)]
'my list is %s' % myList
Then you'll get "my list is [1, 2, 3]
" as your output.
Upvotes: -2
Reputation: 27426
I agree with the previous answer about using list comprehensions to do this, but you could certainly hide that behind a function, if that's what floats your boat.
def is_list(value):
if type(value) in (list, tuple): return True
return False
def list_str(value):
if not is_list(value): return str(value)
return [list_str(v) for v in value]
Just for fun, I made list_str() recursively str() everything contained in the list.
Upvotes: 4
Reputation: 11308
Depending on what you want to use that output for, perhaps __repr__
might be more appropriate:
import unittest
class A(object):
def __init__(self, val):
self.val = val
def __repr__(self):
return repr(self.val)
class Test(unittest.TestCase):
def testMain(self):
l = [A('a'), A('b')]
self.assertEqual(repr(l), "['a', 'b']")
if __name__ == '__main__':
unittest.main()
Upvotes: 4
Reputation: 539
Something like this?
a = [1, 2 ,3]
[str(x) for x in a]
# ['1', '2', '3']
Upvotes: 1
Reputation: 391854
Two easy things you can do, use the map
function or use a comprehension.
But that gets you a list of strings, not a string. So you also have to join the strings together.
s= ",".join( map( str, myList ) )
or
s= ",".join( [ str(element) for element in myList ] )
Then you can print this composite string object.
print 'my list is %s'%( s )
Upvotes: 8
Reputation: 87440
You can use a list comprehension to generate a new list with each item str()'d automatically:
print([str(item) for item in mylist])
Upvotes: 28
Reputation: 12803
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__()
Upvotes: 185