Table of Contents
In this tutorial, we will learn about the Python String join() method with the help of examples.
The join()
string method returns a string by joining all the elements of an iterable (list, string, tuple), separated by a string separator.
Example
text = ['Python', 'is', 'a', 'fun', 'programming', 'language'] # join elements of text with space print(' '.join(text)) # Output: Python is a fun programming language
1. Syntax of String join()
The syntax of the join()
method is:
string.join(iterable)
2. joint() Parameters
The join()
method takes an iterable (objects capable of returning its members one at a time) as its parameter.
Some of the example of iterables are:
- Native data types – List, Tuple, String, Dictionary and Set.
- File objects and objects you define with an
__iter__()
or__getitem()__
method.
Note: The join()
method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join()
method is called) and returns the concatenated string.
3. Return Value from join() method
The join()
method returns a string created by joining the elements of an iterable by string separator.
If the iterable contains any non-string values, it raises a TypeError
exception.
4. Example 1: Working of the join() method
# .join() with lists numList = ['1', '2', '3', '4'] separator = ', ' print(separator.join(numList)) # .join() with tuples numTuple = ('1', '2', '3', '4') print(separator.join(numTuple)) s1 = 'abc' s2 = '123' # each element of s2 is separated by s1 # '1'+ 'abc'+ '2'+ 'abc'+ '3' print('s1.join(s2):', s1.join(s2)) # each element of s1 is separated by s2 # 'a'+ '123'+ 'b'+ '123'+ 'b' print('s2.join(s1):', s2.join(s1))
Output
1, 2, 3, 4 1, 2, 3, 4 s1.join(s2): 1abc2abc3 s2.join(s1): a123b123c
5. Example 2: The join() method with sets
# .join() with sets test = {'2', '1', '3'} s = ', ' print(s.join(test)) test = {'Python', 'Java', 'Ruby'} s = '->->' print(s.join(test))
Output
2, 3, 1 Python->->Ruby->->Java
Note: A set is an unordered collection of items, so you may get different output (order is random).
6. Example 3: The join() method with dictionaries
# .join() with dictionaries test = {'mat': 1, 'that': 2} s = '->' # joins the keys only print(s.join(test)) test = {1: 'mat', 2: 'that'} s = ', ' # this gives error since key isn't string print(s.join(test))
Output
mat->that Traceback (most recent call last): File "...", line 12, in <module> TypeError: sequence item 0: expected str instance, int found
The join()
method tries to join the keys (not values) of the dictionary with the string separator.
Note: If the key of the string is not a string, it raises a TypeError
exception.