How to make print call the __str__ method of Python objects inside a list?

Question:

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

Asked By: benhsu

||

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__()
Answered By: 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])
Answered By: Dan Lew

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 )
Answered By: S.Lott

Something like this?

a = [1, 2 ,3]
[str(x) for x in a]
# ['1', '2', '3']
Answered By: WhatIsHeDoing

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()
Answered By: Horst Gutmann

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.

Answered By: Jeremy Cantrell

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.

Answered By: panagiwtis koligas

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 
Answered By: prosti
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.