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.
Recall:
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

Syntax

string_name.join(iterables)

Parameters:
join() takes an Iterable object, which must return string values on each iterate.
Return Type:
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))

Output

JohnDoeRonDoeHarryDoeGwen
<class 'str'>
  1. The first line of code is defining a list with names i.e. of String
  2. Second-line is defining a string
  3. The third line is assigning for the result
  4. The last two lines are for Output

Type Error

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)

Error

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

Output

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.

Leave a Reply

Your email address will not be published.