Python join () will not join the string representation (__str__) of my object

I'm not sure what I'm doing wrong here:

>>> class Stringy(object):
...     def __str__(self):
...             return "taco"
...     def __repr__(self):
...             return "taco"
... 
>>> lunch = Stringy()
>>> lunch
taco
>>> str(lunch)
'taco'
>>> '-'.join(('carnitas',lunch))
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected string, Stringy found

Given my inclusion of a method __str__()in a Stringy object, shouldn't join()you see lunch as a string?

+5
source share
3 answers

''.join __str__ , . __str__, ( object), join , ( ) - . , str , ( " , ", , "Zen of Python" ).

str unicode, "" . str, "".

+7

str

'-'.join(('carnitas',str(lunch)))

'-'.join(str(x) for x in seq)

'-'.join(map(str, seq))

'carnitas-'+str(lunch)
+12

Call signal for str.join:

S.join(sequence) -> string

Return a string which is the concatenation of the strings in the
sequence.  The separator between elements is S.

Note what sequenceis expected as a string sequence. Many objects have methods __str__, but not all of them (for example, Stringy) are instances str.

The fix, of course, is simple:

'-'.join(('carnitas',str(lunch)))
+1
source

All Articles