Python String Join

The Python join method is one of the String method, which is used to join or concatenate a string with iterables. This Python string join function accepts iterables as an argument and attaches a given separator while joining the strings in a iterable.

In this article, we will show you, how to use this Python Join function to join strings in a List, Dictionary, Set etc with an example of each.

Python string join syntax

The basic syntax of this string join in Python programming language is as shown below

separator.join(iterable)

Python Join strings with spaces

This is a simple example to show you the join function. Here, we declared a tuple of characters a, b and c. Next, we used the space as the separator and the tuple as an argument of the Join function. This will join the tuple items separated by space.

text = ('a', 'b', 'c')
x = ' '.join(text)
print(x)

OUTPUT

Python Join with Delimiter

This is an another example of the join function. Here, we used the comma and – as the separator between the string tuple.

Python Join List elements

In this example, we are using the String Join function to Join the List items. Here, we used the \n (new line) as the separator between the list items. I suggest you to refer to Python List article to understand the list creation.

As you can see from the above screenshot, Join function joined the dictionary keys. This is the default option available in Python. However, you can use the dictionary function values to join the dictionary values.

As you can see from the above screenshot, both the print(seq.join(‘HELLO’)) and print(seq.join([‘H’,’E’, ‘L’, ‘L’, ‘O’])) are returning the same result. This is because, internally, seq.join(‘HELLO’) will be converted to list of characters.

This is an another example of Python string join that can help you to understand the implicit conversion. Here, we used different separators to separate tutorialgateway string.

Python Join string and int

So far, we are working with string data. In this example, we declared a mixed list of string and integer. Next, we used the Python string Join function with $$$ as separator to join the list items. As you can see form the below screenshot, it as throwing an error: TypeError: sequence item 3: expected str instance, int found

There is an alternative approach to work with the mixed lists. Here, we used the map function along with Python string join to achieve the same result. I suggest you to refer Python map function article.