Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about .join()

Tags:

python

I’m new to python and completely confused,

why ','.join('a','b','c')rised an error, a ",".join(['a','b','c'])didn’t.

Why the code below have the same output?

In [3]: ",".join({'a':1,'b':2,'c':3})
Out[3]: 'b,a,c'

In [4]: ",".join({'a':2,'b':1,'c':3})
Out[4]: 'b,a,c'

In [5]: ",".join({'a':3,'b':2,'c':1})
Out[5]: 'b,a,c'
like image 365
user18861 Avatar asked Dec 24 '22 04:12

user18861


1 Answers

The docs on str.join state that the method takes an iterable which is any type that can be iterated over (list, tuple, etc.):

str.join(iterable)¶

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.


In your first example, you pass three arguments to a method which expects one so receive a TypeError, whereas you use the method as intended in the example where you pass a list (indicated so through the use of square brackets). In your typed examples, you are passing dictionaries which are also iterable, however, when iterated over, they yield their keys (note: the order is undetermined). So the keys of say: {'a':1,'b':2,'c':3} are: 'a', 'b' and 'c' and since these are all strings, the method works fine to join them together with a comma

like image 109
Joe Iddon Avatar answered Jan 11 '23 07:01

Joe Iddon