gcb gcb - 2 years ago 64
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)

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download