Python String join() Method (original) (raw)

Last Updated : 12 Nov, 2024

The join() method in Python is used to concatenate the elements of an iterable (such as a list, tuple, or set) into a single string with a specified delimiter placed between each element.

Lets take a simple example tojoin list of string using join() method.

Joining a List of Strings

In below example, we use **join() method to combine a **list of strings into a **single string with each string separated by a **space.

Python `

a = ['Hello', 'world', 'from', 'Python'] res = ' '.join(a) print(res)

`

Output

Hello world from Python

Table of Content

Syntax of join()

separator.join(iterable)

Parameters:

Return Value:

Examples of join() Method on Different Data Types

Below are examples of how join() method works with different data types.

Using join() with Tuples

The **join() method works with any iterable containing strings, including **tuples.

Python `

s = ("Learn", "to", "code")

Separator "-" is used to join strings

res = "-".join(s) print(res)

`

Using join() with set

In this example, we are joining set of String.

Python `

s = {'Python', 'is', 'fun'}

Separator "-" is used to join strings

res = '-'.join(s) print(res)

`

**Note: Since **sets are unordered, the resulting string may appear in any order, such as “fun is Python” or “Python is fun”.

Using join() with Dictionary

When using the **join() method with a dictionary, it will only join the **keys, not the values. This is because **join() operates on iterables of strings and the default iteration over a dictionary returns its **keys.

Python `

d = {'Geek': 1, 'for': 2, 'Geeks': 3}

Separator "_" is used to join keys into a single string

res = '_'.join(d)

print(res)

`