Python string join() method with example

The join() method in Python is a string method used to concatenate elements from an iterable (such as a list or a tuple) into a single string. It takes the iterable as an argument and returns a new string where the elements of the iterable are joined together by the string on which the join() method is called.

Syntax:

string_to_join.join(iterable)

How to use the join() method:

my_list = ['Hello', 'world', '!', 'I', 'am', 'Python']
joined_string = ' '.join(my_list)
print(joined_string)

Output:

Hello world ! I am Python

Example 1

Joining a List of Numbers as Strings.

numbers = [1, 2, 3, 4, 5]
number_string = '-'.join(str(num) for num in numbers)
print(number_string)

Output:

1-2-3-4-5

Example 2

Creating a CSV String from a List of Data.

data = ['John', 'Doe', '30', 'Software Engineer']
csv_string = ','.join(data)
print(csv_string)

Output:

John,Doe,30,Software Engineer

Example 3

 Joining URL Path Segments.

base_url = 'https://example.com'
path_segments = ['api', 'v1', 'users']
url = '/'.join([base_url] + path_segments)
print(url)

Output:

https://example.com/api/v1/users