In Python, I can do:
>>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c'
Is there any easy way to do the same when I have a list of objects?
>>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(), Obj()] >>> ', '.join(list) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, instance found
Or do I have to resort to a for loop?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.
We can use python string join() function to join a list of strings. This function takes iterable as argument and List is an interable, so we can use it with List.
String join is significantly faster then concatenation. Why? Strings are immutable and can't be changed in place. To alter one, a new representation needs to be created (a concatenation of the two).
You could use a list comprehension or a generator expression instead:
', '.join([str(x) for x in list]) # list comprehension ', '.join(str(x) for x in list) # generator expression
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With