Concatenate Strings using python join() function

python-join

Python join : The python join() function is a powerful function for combining strings with each other. You probably know the concatenation with the nice arithmetic “+” which allows you to do something similar but with some subtleties that we will see later.

Joining string using join() function

The python join() function returns a string in which the string elements of the sequence have been joined by str separator.

The syntax of the function is as follows:

str.join(seq)
 

This function returns a string, which corresponds to the concatenation of the strings separated by the parameter filled in the variable seq.

Let’s try to join now the word “123” and “456”. What do you think the syntax will be?

Nothing more simple, just pass the function in the first string and put the second word as a parameter of the join() function as shown below :

texte = "123".join("456")
print('String: {0}'.format(texte))

Output :

String: 412351236

Joining iterable using python join()

The most common use case for this function is when you have an iterable (list, dictionary, tuple, or string) composed only of strings (otherwise the function will return an Type Error exception) and you want to combine them into a single string.

Python join tuple

Here is an example to show that can use the function on a string tuple as well :

keyword = ('AMIRA','DATA','PYTHON')
sep = ','
text = sep.join(keyword)
print('Values: {0}'.format(text))
 

Output:

Values: AMIRA,DATA,PYTHON

Python Join list

This function makes it possible to combine the items in a list with each other:

keyword = ['AMIRA', 'DATA', 'PYTHON']
sep = ','
result = sep.join(keyword)
print('String: {0}'.format(result))
 

Output:

String: AMIRA,DATA,PYTHON

In the example, we join each item in the list with a comma.

Python Join Dictionnary

We can also use the function on a dictionary to combine keys or values with a separator :

keyword = {'1':'AMIRA', '2':'DATA', '3':'PYTHON'}
sep = ','
keys = sep.join(keyword.keys())
values = sep.join(keyword.values())
print('Keys: {0}'.format(keys))
print('Values: {0}'.format(values))
 

Output :

Keys: 1,2,3
Values: AMIRA,DATA,PYTHON

Summary

As you can see, this feature is very powerful for combining iterables. It’s easy to use and allows you to quickly get to grips with it.

Feel free to ask me in comments if you have problems using this function. I will be happy to answer as soon as possible 🙂

If you want to learn more about python, you can read this book (As an Amazon Partner, I make a profit on qualifying purchases) :

Go to the main menu

Published
Categorized as Python

By ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Leave a comment

Your email address will not be published.