What is the join method in Python

The join method in Python takes elements of an iterable data structure and connects them together using a particular string connector value.

How does join work?

The join method in Python is a string method which connects elements of a string iterable structure, which also contains strings or characters (array, list, etc.) by using a particular string as the connector.

Syntax

Understanding through illustration

The illustration below shows how this method works.

The iterable whose elements are to be joined
1 of 4

Examples

Now that we know how the function works, let’s look at examples to further enhance our understanding.

1. Connecting elements using an empty string

This will join the elements in array using an empty string between each element.

array = ['H','E','L','L','O']
connector = ""
joined_string = connector.join(array)
print(joined_string)

2. Connecting using a comma ,

This will join the elements in array using a comma between each element.

array = ['1','2','3','4','5']
connector = ","
joined_string = connector.join(array)
print(joined_string)

3. Connecting without declaring a separate string variable

This shows how elements can be connected by a dash, without having to create a separate string variable for the connector.

array = ['W','O','R','L','D']
print("-".join(array))

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved