Custom string joining

Claudiu Popa cpopa at bitdefender.com
Tue May 10 01:51:55 EDT 2011


Hello Terry,

Thanks, I understand now.

Tuesday, May 10, 2011, 2:16:24 AM, you wrote:

> On 5/9/2011 4:25 PM, Claudiu Popa wrote:

>> I  already told in the first post that I've implemented __str__ function,
 >> but it doesn't seems to be automatically called.

> No, Python does not auto-coerce to strings (only between numbers).
> You have to be explicit by calling str. Karim's statement "You just have
> to implement __str__() python special method for your "custom_objects".
> " means that str will then work.

>> For instance, the following example won't work:
>>
>>>>> class a:
>>          def __init__(self, i):
>>                  self.i = i
>>          def __str__(self):
>>                  return "magic_function_{}".format(self.i)
>>>>> t = a(0)
>>>>> str(t)
>> 'magic_function_0'
>>>>> "".join([t])

> print('\n'.join(str(ob) for ob in [a(0), a(1), a(None)]))

> magic_function_0
> magic_function_1
> magic_function_None




-- 
Best regards,
 Claudiu




More information about the Python-list mailing list