Python __str__ and lists

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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__()

Solution 2 - Python

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

print([str(item) for item in mylist])

Solution 3 - Python

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 )

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

Something like this?

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

Solution 7 - Python

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 

Solution 8 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbenhsuView Question on Stackoverflow
Solution 1 - PythonDavid BergerView Answer on Stackoverflow
Solution 2 - PythonDan LewView Answer on Stackoverflow
Solution 3 - PythonS.LottView Answer on Stackoverflow
Solution 4 - PythonHorst GutmannView Answer on Stackoverflow
Solution 5 - PythonJeremy CantrellView Answer on Stackoverflow
Solution 6 - PythonWhatIsHeDoingView Answer on Stackoverflow
Solution 7 - PythonprostiView Answer on Stackoverflow
Solution 8 - Pythonpanagiwtis koligasView Answer on Stackoverflow