Home »
Python
Why is it string.join(list) instead of list.join(string) in Python?
Python string.join(list) vs list.join(string): Here, we are going to learn why is it string.join(list) instead of list.join(string) in Python?
Submitted by Sapna Deraje Radhakrishna, on November 23, 2019
join() is a string method and while using it the separator string iterates over an arbitrary sequence, forming string representations of each of the elements, inserting itself between the elements.
Concisely, it's because join and string.join() are both generic operations that work on any iterable and is a string method.
Because it is a string method, the join() can work for the Unicode string as well as plain ASCII strings.
Example Usage of string.join(list)
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> test_string = "test"
>>> test_string.join("1234")
'1test2test3test4'
>>>
In the above example, the string "test" is joined with every character provided as a join argument.
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> test_string = "test"
>>> test_string.join("---")
'-test-test-'
>>>