Python __str__ and lists

Solution 1:

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:

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:

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:

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