How can I use the join() method in Python?

When looking at a Python program written by a colleague of mine I noticed that they used join(). What does join() do in Python?

The join() method is one of the methods provided by the string data type in Python. The join method allows generating a string from the elements of an iterable (e.g. a list, a tuple, or a set). When you call the join() method you have to provide a separator string that separates the elements of the iterable in the final string returned by join().

This will become very clear by going through the examples of code below.

What is the String join() Method in Python?

The join() method is a Python string method used to join all the elements of an iterable (string, list, tuple, dictionary, or set) into a single string. A separator is specified as part of the join() method and it’s used to separate each element of the iterable in the final string.

Below you can see the syntax of the join() method:

What is the String join() Method in Python?

The elements of the iterable passed to the join() method must be strings. If the iterable contains non-string values, the Python interpreter raises a TypeError.

Why Would You Use the Python string join() Method?

You use the join() method in Python if you want to join the elements of an iterable like a list of strings to create a single string.

Imagine, for example, that you have a list of words and you want to create a single string by joining all the words in the list separated by spaces. In this case, the space would be the separator to be passed to the string join() method.

You can see an example of how this works in the video below:

Also, the fact that you can choose the separator to be added between each element of the iterable makes the join() method a flexible approach to generating Python strings.

Is join() a Python String Method?

The join() method is a method of the string data type in Python. This means that join() is a function associated with objects of type string.

To call the join() method on a string (the separator) you use the dot notation as shown below:

separator.join(iterable)

And here is an example of Python code that calls the join() method:

test_string = " ".join(['Test', 'the', 'join()', 'method'])
print(test_string)

[output]
'Test the join() method'

In this example, we have used the space character as the separator.

To print the value of the string returned by the join() method you are using the Python print() function.

How Do You Join a List into a String?

Python provides the join() method to concatenate the elements of a list of strings using a character as a separator.

The join method does in a single line what otherwise you would have to do using a for loop and multiple lines of code.

Let’s take the following list of strings and use join() to generate a single string from it:

modules = ["Python modules:", "Pandas", "subprocess", "json"]
print(" ".join(modules))

[output]
Python modules: Pandas subprocess json     

And here is what the final string looks like if you use the newline character (“\n”) as the separator:

modules = ["Python modules:", "Pandas", "subprocess", "json"]
print("\n".join(modules))

[output]
Python modules:
Pandas
subprocess
json

As you can see the join() method is applied to the character used as a separator and takes as argument the list.

The iterable you pass to the join() method cannot contain non-string elements. For example, let’s add a number to the list above and see what happens:

modules = ["Python modules:", "Pandas", "subprocess", "json", 14578]
print("\n".join(modules))

[output]
Traceback (most recent call last):
  File "/opt/codefathertech/tutorials/join_method.py", line 5, in <module>
    print("\n".join(modules))
TypeError: sequence item 4: expected str instance, int found

The Python interpreter raises a TypeError because the item with index 4 in the sequence (iterable) is expected to be a string but it’s an integer instead.

How Do You Join a Tuple into a String?

The Python string join() method can be applied to any iterable, this means it also works with Python tuples.

The example below tests the join() method with a Python tuple:

modules = ("Python modules:", "Pandas", "subprocess", "json")
print("\n".join(modules))

[output]
Python modules:
Pandas
subprocess
json      

The output is exactly the same as you have seen when passing a Python list to the join() method.

Also, the join() method can only be used with a tuple of strings. Here is what happens if you apply the join() method to a tuple of integers:

numbers = (10, 20, 30, 40, 50)
print(" ".join(numbers))

[output]
Traceback (most recent call last):
  File "/opt/codefathertech/tutorials/join_method.py", line 5, in <module>
    print(" ".join(numbers))
TypeError: sequence item 0: expected str instance, int found

Python raises a TypeError because it expects a string but it has found an integer instead.

How Do You Join a Set into a String?

You can use the Python string join() method to concatenate (join) the elements of a set. Also, considering that elements in a set are unordered, the final string returned by the join() method can be different every time you execute your code.

The example below tests the join() method with a Python set:

modules = {"Python modules:", "Pandas", "subprocess", "json"}
print("\n".join(modules))

[output]
Python modules:
Pandas
subprocess
json      

The output is exactly the same as we have seen when passing a Python list to the join() method. But it could just be a coincidence due to the unordered nature of sets.

Let’s execute this code multiple times to see if the output changes considering that we are working with a Python set.

# TEST 2 OUTPUT
Pandas
Python modules:
subprocess
json

# TEST 3 OUTPUT
Pandas
json
Python modules:
subprocess

You can see that the final string generated by the join() method changes every time based on how the order of the elements in the set changes at every execution of the code.

Let’s see what happens when joining a set of numbers:

numbers = {10, 20, 30, 40, 50}
print(" ".join(numbers))

[output]
Traceback (most recent call last):
  File "/opt/codefathertech/tutorials/join_method.py", line 5, in <module>
    print(" ".join(numbers))
TypeError: sequence item 0: expected str instance, int found

Once again we see a TypeError caused by the fact that the string join() method can only be used to join strings.

How Do You Join String Characters in Python?

Before I have explained that you can pass an iterable to the join() string method. A Python string is also an iterable so we should be able to also pass a string() to the join() method.

Let’s try this out!

word = "python"
print(" ".join(word))

[output]
p y t h o n

In this code, we have used the space as the separator and passed the string word to the join() method.

The result is a string made of each character in the string word separated by space.

This shows that you can also use the join() method to add a separator between each character of a string.

Let’s add some numbers to this string…

Are you expecting to see the same error we have seen before when passing a list, tuple, or set containing numbers to the join() method?

word = "python3.11"
print(" ".join(word))

[output]
p y t h o n 3 . 1 1

We don’t see any errors after adding numbers to the string word because each number is a character and not an integer.

You can confirm this by using the Python type() built-in function and a for loop.

word = "python3.11"

for character in word:
    print(character, type(character))

[output]
p <class 'str'>
y <class 'str'>
t <class 'str'>
h <class 'str'>
o <class 'str'>
n <class 'str'>
3 <class 'str'>
. <class 'str'>
1 <class 'str'>
1 <class 'str'>

How Do You Join a Python Dictionary into a String?

In this section, we will explore what happens when you pass a Python dictionary to the string join() method.

Start by creating a dictionary:

numbers = {"one": 1, "two": 2, "three": 3}

Then pass this dictionary to the join() method and use the space character as the separator.

print(" ".join(numbers))

[output]
one two three

You can see in the output of the join() method the keys of the dictionary.

A dictionary can be passed as an iterable to the join() method. The join() method joins the keys of the dictionary and returns a string made of the keys separated by the character the join() method is applied to.

Let’s switch keys and values in the dictionary and see if anything changes.

numbers = {1: 'one', 2: 'two', 3: 'three'}
print(" ".join(numbers))

[output]
Traceback (most recent call last):
  File "/opt/codefathertech/tutorials/join_method.py", line 5, in <module>
    print(" ".join(numbers))
          ^^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found

The execution of this Python code fails with a TypeError because the join() method tries to concatenate the keys of the dictionary that in this example are integers instead of strings.

Is the String join() Method Faster Than += in Python?

The Python string join() method is faster than the += operator when it comes to concatenating strings.

Let’s go through two examples to show how the two approaches compare to each other with a small iterable (100 elements) and a bigger iterable (100,000 elements).

Let’s start with 100 elements:

import time

# Using the join() method
start_time = time.time()
test_string = ', '.join(['test' for _ in range(100)])
end_time = time.time()
print('Time using the join() method: ', end_time - start_time)

# Using the += operator
start_time = time.time()
s = ''
for _ in range(100):
    test_string += 'test'
end_time = time.time()
print('Time using the += operator: ', end_time - start_time)

In the code above we import the time module and then calculate the difference between end_time and start_time to compare how long the join() method takes compared to the += operator.

Time using the join() method:  1.2874603271484375e-05
Time using the + operator:  2.7894973754882812e-05

From this output, you can see that the join() method is faster than the += operator.

Let’s see if the difference in time increases when we increase the number of elements in the iterable to 100,000:

Time using the join() method:  0.005889892578125
Time using the + operator:  0.017504215240478516

Once again, the join() method is faster than the += operator.

The reason why the string join() method is faster than the + operator when concatenating strings is that the Python string is an immutable data type. This means that after a string is created it cannot be modified and every time you use the += operator Python creates a new string. On the other side, the join() method performs the string concatenation in one operation.

Conclusion

The Python join() method is very useful for string concatenation and offers performance advantages compared to the approach based on the += operator.

Remember that to be able to use the join() method you have to work with an iterable of strings. If the iterable contains numbers Python will raise a TypeError exception as you have seen multiple times in the examples we have covered in this tutorial.

Continue practicing the string join() method and pretty soon it will become one of the main constructs you will use in your Python programs.

Related articles: if you want to learn more about the concatenation of strings read this CodeFatherTech tutorial about concatenating strings in Python.

Leave a Comment