How to concatenate or append strings in Python

If you are looking for answer how to append strings in Python, you are on the right page.

There are several different ways how to concatenate strings in Python. Pick up the right one which will most suit to your code purpose.

Concatenation with + operator

First way is to use + operator for concatenation:

Since everything in Python is an object and Strings in Python in immutable, this solution is unoptimized. Every time the + operator is called reference on new object is assigned to variable. It is sufficient to use it for simple programs. For more complex programs requiring building lots of text I would recommend to use less resource requiring approach.

Building strings with .append()

Second option is to use approach for building up string from a list. If you are familiar with Java’s OOP approach, StringBuilder is similar way to build strings in Java.

Idea is simple. First create list of all append-able strings and then use str.join() method to concatenate them all at the end:

Difference between string concatenation with + operator and building string over append is in performance. Despite in short text the performance difference is none, in longer text building strings over append will create new string in one go while + operator build string over and over, repetitively.

.append vs. + operator

Here I made a small code to test which operation for concatenating strings is faster:

I run the code on my Mac Pro which is mid 2015 configuration. The results are in microseconds:

Rounds.append+ operator
1 00000
1 000 000150185
10 000 00014601980

It is obvious that for small number of rounds there is no difference between .append or + operator. But with increasing complexity (increasing number of rounds) appending strings to list will be slightly faster by nearly quarter.

Using .join()

You can also use strings in join function directly:

Padding

One of the most simplest way is just pad strings into the new string. We can use either the % operator for padding in exact order or use .format() method to define unique keywords and place them in arbitrary order:

 

Using __add__ method

Marvel of Python is its neat variability. Since everything in Python is the object we can use object’s __add__ method for concatenation. Using s1.__add__(s2) is identical with using a+b.

When you concatenate strings using the + operator, Python will call the __add__ method while on the string on the left side passing the right side string as a parameter. So using this method on simple strings is code overkill.

It make much more sense to use it for concatenation object properties.

As we saw in the previous section there are several ways how to append strings or concatenate them together. You can use literally any provided solution here, it only depends on a purpose and necessary complexity you want to implement in your program.