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:

s  = 'And '
s += 'now '
s += 'something '
s += 'completely '
s += 'different.'
print(s)

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:

l = []
l.append('And')
l.append('now')
l.append('something')
l.append('completely')
l.append('different.')
s = ''.join(l)
print(s)
# And now something completely different.

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:

import time

# append in loop
app_start = int(round(time.time() * 1000))
l = []
for _ in range(0,10000000,1):
    l.append('a')
string = ''.join(l)
app_end = int(round(time.time() * 1000))
print('With append: %s' % (app_end - app_start))

# conc with +
plus_start = int(round(time.time() * 1000))
s = ''
for _ in range(0,10000000,1):
    s += 'a'
plus_end = int(round(time.time() * 1000))
print('With +: %s' % (plus_end - plus_start))

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

Rounds .append + operator
1 000 0 0
1 000 000 150 185
10 000 000 1460 1980

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:

s1 = "And now something "
s2 = "completely different."
s = " ".join((s1, s2))
print(s)
# And now something completely different.

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:

s1 = 'And now something'
s2 = 'completely different'

new_s1 = "Sentence: %s %s" % (s1, s2)
print(new_s1)
# Sentence: And now something completely different.

new_s2 = "Sentence: {string2} {string1}".format(string1=s1, string2=s2)
print(new_s2)
# Sentence: completely different And now something.

 

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.

s1='And now something '
s2='completely different.'
s = s1.__add__(s2)
print(s)
# Sentence: And now something completely different.

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.

class Sentence(object):
  def __init__(self, part):
     self.part = part
  def __add__(self, other):
     total = self.part + ' ' + other.part
     return Sentence(total)

  def __radd__(self, other):
     if other == 0:
       return self
     else:
       return self.__add__(other)

  def __str__(self):
     return "Sentence: %s" % (self.part)

s1 = Sentence('And now')
s2 = Sentence('something completely different.')
print(s1)
# Sentence: And now
print(s2)
# Sentence: something completely different.

s = s1 + s2
print(s)
# Sentence: And now something completely different.

super_s = sum([s, s1, s2])
print(super_s)
# Sentence: And now something completely different. And now something completely different.

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.

This entry was posted in Language basics and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.