gcb gcb - 5 months ago 5
Python Question

how to join into a string a list of objects that can be converted to string?

i have a list of objects that do have a

method. and i want to get a string of all the objects in a list. but when i do the (obvious?)
' '.join(my_list)
i get an error
TypeError: sequence item 0: expected str instance, LogEntry found

Btw, the goal of this is to simply feed a Tkinter Listbox content with log entries. If there are better ways to do that, let me know. but here is the code i have

class LogEntry():
def __init__(self, msg, type):
def __str__(self):
return self.msg

my_log = [LogEntry("123", WARN), LogEntry("abc", DEBUG) ]

print "\n".join(my_log)


Use list comprehension to make a list of __str__'s result on each object:

my_log_strs = [str(log) for log in my_log]

Or map:

my_log_strs = map(str, my_logs)

Now you can:

print "\n".join(my_log_strs)

Or more concisely:

print "\n".join(str(log) for log my_log)