String join() Method in Python
This article is about the String join() Method in Python and how to use it with different iterable objects of Python.
join() is a string method whose return type is also a string in which elements of the argument have been joined by the provided string.
Python strings are those entities that are enclosed within a single quotation (‘string’) or double quotation(“string”).
Iterable is an object those can be lopped over with the use of for loop, i.e. they are the sequence that returns their member on each iterate. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterable.
Working of join() in Python
join() takes an Iterable object, which must return string values on each iterate.
The return type of the join() is a String
Let’s See with an Example
list=['John','Ron','Harry','Gwen'] string='Doe' result=string.join(list) print(result) print(type(result))
JohnDoeRonDoeHarryDoeGwen <class 'str'>
- The first line of code is defining a list with names i.e. of String
- Second-line is defining a string
- The third line is assigning for the result
- The last two lines are for Output
If the parameter contains any non-string, It raises a TypeError exception. That can also be handled using a try-except block.
tu=("John",10,11) string='DOE' result=string.join(tu) print(result)
Traceback (most recent call last): File "<string>", line 5, in <module> TypeError: sequence item 1: expected str instance, int found
Using join() with Non-String
Users can use non-string objects by converting them into strings Explicitly using a predefined function str().
list=[10,20,30,40,50] string='-->' result=string.join(str(x) for x in list) print(result) print(type(result))
10-->20-->30-->40-->50 <class 'str'>
Thus, This is all about the Python String join() Method with some variations, you can also give it a try with more variations.