Python String join()

Python String join() is used to join all items in given iterable with this string in between them, and returns the resulting new string.

In this tutorial, we will learn the syntax and examples for join() method of String class.

Syntax

The syntax to call join() method on string x in Python is

</>
Copy
x.join(iterable)

where

ParameterRequired / OptionalDescription
iterableRequiredA Python iterable like List, Tuple, Set, etc.

Examples

In the following program, we take a list of strings, and join these items in list with the string '--' using join() method.

Example.py

</>
Copy
x = ['apple', 'banana', 'cherry']
result = '--'.join(x)
print(result)

Output

apple--banana--cherry

In the following program, we take a tuple of strings, and join these items in tuple with the string ',' using join() method.

Example.py

</>
Copy
x = ('apple', 'banana', 'cherry')
result = ','.join(x)
print(result)

Output

apple,banana,cherry

In the following program, we take a Set of strings, and join these items in the Set with the string ' ' (single space) using join() method.

Example.py

</>
Copy
x = {'apple', 'kiwi', 'mango'}
result = ' '.join(x)
print(result)

Output

mango kiwi apple

Conclusion

In this Python Tutorial, we learned how to join the items of given iterable and form a string using join() method, with examples.