Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's join() won't join the string representation (__str__) of my object

Tags:

python

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 the __str__() method in the Stringy object, shouldn't join() see lunch as a string?

like image 245
ampledata Avatar asked Aug 04 '10 23:08

ampledata


1 Answers

no you have to convert it to str yourself

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

if you have to do it for a whole sequence of items

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

or

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

for your particular case you can just write

'carnitas-'+str(lunch)
like image 158
John La Rooy Avatar answered Sep 30 '22 04:09

John La Rooy