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-'
>>>






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.