Python string.join(list) with an array of objects
To concatenate an object array into one string in Python, a transformation of objects to strings is necessary. Use list comprehension to do this efficiently:
Or, the map function can offer an equally concise solution:
In both cases, __str__ of each object is invoked, and the objects are tied together into one single, space-separated string.
Object transformation 101
Every object is equipped with a __str__ method that defines how it appears as a string. This representation is called upon whenever you use str(obj). If not specified within your objects, Python will default to using __repr__:
Calling str() on an object of MyObject now gets you Custom(value).
Play nice with built-ins
Avoid the naming temptation of list as it overshadows Python's built-in list type. Choose clear and descriptive names instead:
Custom strings for the connoisseur
For users desiring more finesse, a custom subclass of str can override the join method to handle non-string objects:
By creating an instance of MyStr, you can join objects fluently:
Str and repr: a harmonious duet
It is often sensible to make __repr__ align with __str__ for consistent outputs:
Now repr(obj) will match the str(obj) output, making debugging look less like debugging.
Was this article helpful?