Explain Codes LogoExplain Codes Logo

Python string.join(list) with an array of objects

python
object-transformation
string-methods
best-practices
Alex KataevbyAlex Kataev·Mar 3, 2025
TLDR

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:

# Drum roll, please 🥁... joined_string = ' '.join([str(obj) for obj in objects_array])

Or, the map function can offer an equally concise solution:

# And now for our next trick... joined_string = ' '.join(map(str, objects_array))

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__:

class MyObject: def __init__(self, value): self.value = value def __str__(self): return f'Custom({self.value})' # Ha, I pull the strings now!

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:

# Not all heroes wear capes; some choose descriptive variable names. my_objects = [MyObject(1), MyObject(2)] joined_string = ' '.join(str(obj) for obj in my_objects)

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:

# When str isn't enough, you make your own! class MyStr(str): def join(self, iterable): strings = (str(item) for item in iterable) return super().join(strings)

By creating an instance of MyStr, you can join objects fluently:

# Yes, alongside pet rocks, I also collect custom strings. joiner = MyStr(' - ') joined_string = joiner.join(my_objects)

Str and repr: a harmonious duet

It is often sensible to make __repr__ align with __str__ for consistent outputs:

class Object: def __init__(self, value): self.value = value def __str__(self): return f'Object({self.value})' __repr__ = __str__ # Duet mode engaged.

Now repr(obj) will match the str(obj) output, making debugging look less like debugging.