Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string.join(list) on object array rather than string array

Tags:

python

list

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?

like image 928
Mat Avatar asked Jan 31 '09 00:01

Mat


People also ask

How do you join a list of objects in Python?

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.

How do you join a string array in Python?

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.

Can you use .join on a list?

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.

Is join faster than concatenation Python?

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).


1 Answers

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 
like image 92
Adam Rosenfield Avatar answered Oct 08 '22 07:10

Adam Rosenfield