Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is any magic method called on an object in a list during join()?

Joining a list containing an object - is there any magic method I could set to convert the object to a string before join fails?

', '.join([…, Obj, …])

I tried __str__ and __repr__ but neither did work

like image 905
Hoffmann Avatar asked May 31 '13 13:05

Hoffmann


1 Answers

Nope, there's no join hook (although I've wanted this feature as well). Commonly you'll see:

', '.join(str(x) for x in iterable)

or (almost) equivalently:

', '.join(map(str,iterable))
', '.join([str(x) for x in iterable])

(Note that all of the above are equivalent in terms of memory usage when using CPython as str.join implicitly takes your generator and turns it into a tuple anyway.)

like image 146
mgilson Avatar answered Nov 15 '22 17:11

mgilson