Python language basics 36: string concatenation using the join method


In the previous post we discussed how to use the ‘in’ operator to determine whether a certain element is found in a collection. You can apply this operator – and its negation ‘not in’ – on all collection types including strings.

In this post we’ll look at a useful String function called ‘join’ to concatenate bits of strings into a single one.

String concatenation

Basic string concatenation is performed using the addition operator ‘+’:

combined = "Welcome" + " to" + " my blog " + "dear " + "readers"

‘combined’ will become “Welcome to my blog dear readers” as expected. Do you recall that strings are immutable in Python – and in fact all major programming languages? The problem with the above statement is that it creates multiple strings in succession as the ‘+’ operator is applied:

Welcome to
my blog
Welcome to my blog


‘combined’ will at the end point at the string “Welcome to my blog dear readers” in memory. The other values will be kept in memory until the garbage collector cleans them up as unused resources without references.

A more efficient solution is the join function although its usage is a bit strange at first sight. It operates directly on a string which will become a string delimiter. Here’s an example:

combined = '|'.join(("This", "is", "a", "delimited", "string"))

combined will become:


Can you guess why we needed 2 pairs of parenthesis? The inner pair is the way to declare the tuple collection which we discussed in this post. The join method takes only one argument and it must be a collection. Hence we need to wrap the strings to be concatenated in a collection. A string list works equally well:

combined = '|'.join(["This", "is", "a", "delimited", "string"])

‘combined’ will be the same as above.

How can we build the same “Welcome to my blog dear readers” like above? What is the delimiter here? It’s of course the space character ‘ ‘:

combined = ' '.join(["Welcome", "to", "my", "blog", "dear", "readers"])

‘combined’ will evaluate to “Welcome to my blog dear readers” as it was intended.

Read the next part here.

Read all Python-related posts on this blog here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: