Concatenate Strings in Python [With Examples]

Knowing how to concatenate Python strings is something you need when writing your applications. Let’s see the options available to do that.

With Python you can concatenate strings in different ways, the basic one is with the + operator. If you have two strings (string1 and string2) you can concatenate them using the expression string1 + string2. Python also provides the format() method to concatenate multiple strings together.

It’s time for some examples!

How Do You Concatenate Strings in Python?

The first and most basic way to concatenate two or more Python strings is by using the + operator.

For example, let’s define two variables of type string and concatenate them using the + operator.

>>> string1 = "I like"
>>> string2 = "Python"
>>> string1 + string2
>>> 'I likePython'         

We have used the + to concatenate two strings but the result is not exactly what we expected considering that the words like and Python should be separated by a space.

Using the + operator we can also concatenate more than two strings, in this case, we can also concatenate an additional string that contains a single space (” “).

>>> string3 = " "
>>> string1 + string3 + string2
'I like Python'         

It looks better now.

Thinking about it, there’s no point in storing a single space in the variable string3, so we can simply write:

>>> string1 + " " + string2
'I like Python'         

Concatenate Strings Over Multiple Lines

What if we have a few strings and we want to create a single string that spans across multiple lines?

We can do that by separating the strings with the newline character ( \n ) instead of using a space character as we have done in the previous example:

>>> string1 = "Python modules:"
>>> string2 = "Pandas"
>>> string3 = "subprocess"
>>> string4 = "json"
>>> print(string1 + "\n" + string2 + "\n" + string3 + "\n" + string4)
Python modules:
Pandas
subprocess
json                 

You can see that each string is printed at the beginning of a new line.

Let’s say these four strings are inside a list, we could use a for loop to have a similar result:

>>> strings = ["Python modules:", "Pandas", "subprocess", "json"]
>>> for string in strings:
        print(string)         

Python modules:
Pandas
subprocess
json

In this case, we haven’t specified the newline character in the print statement inside the for loop because the Python print function implicitly adds a newline character at the end of a string.

To remove the implicit newline added at the end of a string by the Python print function you can pass an extra parameter called end.

>>> for string in strings:
        print(string, end='')         

Python modules:Pandassubprocessjson

At this point, we could include the newline character using the + operator in the same way we have done it before:

>>> for string in strings:
        print(string + "\n", end='')  
       
Python modules:
Pandas
subprocess
json

This is just an exercise to learn how the print function and the + operator work.

In a real program, you wouldn’t pass the extra “end” parameter and then concatenate the newline character considering that this is something the print function does by default anyway.

Later in this tutorial, you will learn a better way to concatenate the elements of a list of strings into a single string.

Concatenating a String and a Float

The logic explained for integers in the previous section also applies to other types of numbers, for example floating-point numbers.

If we try to concatenate strings with a float we also get a TypeError back, just with a slightly different error message compared to before: can only concatenate str (not “float”) to str.

>>> string1 + " " + 3.3 + " " + string2
Traceback (most recent call last):
  File "", line 1, in 
    string1 + " " + 3.3 + " " + string2
TypeError: can only concatenate str (not "float") to str         

Once again we can convert the float into a string using the str() function:

>>> string1 + " " + str(3.3) + " " + string2
"Let's concatenate 3.3 strings"         

Now you know how to concatenate strings and numbers in Python.

Concatenate Strings in a For Loop

A common scenario is having to create a string from a list also based on specific conditions that have to be met by the elements of the list.

For example, let’s say we have a list of domains and we want to create a string that contains all the domains except two of them.

This is something we would do using a Python for loop:

>>> domains = ["codefather.tech", "amazon.com", "bbc.com", "cnn.com"]
>>> skip_domains = ["amazon.com", "bbc.com"]
>>> final_domains = ""
>>> for domain in domains:
        if domain not in skip_domains:
            final_domains += domain + "\n"    
>>> print(final_domains, end='')
codefather.tech
cnn.com         

The list skip_domains is used to filter out domains we don’t want to include in the final string.

Also notice that to generate the string final_domains we are using the operator += that concatenates what’s on the right side of the equal sign to the existing value of the final_domains string.

Here is an example to clarify this:

>>> final_domains = "codefather.tech\n"
>>> final_domains += "cnn.com" + "\n"
>>> print(final_domains, end='')
codefather.tech
cnn.com                  

The expression using += can also be written as follows:

>>> final_domains = "codefather.tech\n"
>>> final_domains = final_domains + "cnn.com" + "\n"
>>> print(final_domains, end='')
codefather.tech
cnn.com         

So, the += operator is a more concise way to concatenate strings to an existing string and store the result in the existing string.

Concatenate Strings Using the Python Format Method

The + operator allows to concatenate strings but this doesn’t mean it’s the best way to do string concatenation in Python.

The following example shows why…

Imagine you want to concatenate multiple strings and variables:

>>> first_number = 7
>>> second_number = 3
>>> print("The difference between " + str(first_number) + " and " + str(second_number) + " is " + str(first_number - second_number))
The difference between 7 and 3 is 4     

Look at the expression we had to write to print a very simple string.

It’s definitely quite messy…

…it’s also very easy to make mistakes with all the spaces, plus signs and calls to the str() function.

There’s a better way to do this using the string method format().

How to Concatenate a Python List using the format() method

Look at the official Python documentation above…

We can define a single string and use curly braces {} in the string where we want to specify the value of a variable.

Let’s rewrite our example:

>>> print("The difference between {} and {} is {}".format(first_number, second_number, first_number - second_number))
The difference between 7 and 3 is 4       

That’s so much better!

Using the Python Format Method with Positional Arguments

When using the string format() method we can also specify numeric indexes between curly braces.

These indexes represent positional arguments passed to the format method.

Here is an example:

>>> print("The difference between {0} and {1} is {2}".format(first_number, second_number, first_number - second_number))
The difference between 7 and 3 is 4         

The indexes 0, 1, and 2 refer to the first, second, and third parameters passed to the format method.

To show better how this works, let’s swap index 0 and index 2:

>>> print("The difference between {2} and {1} is {0}".format(first_number, second_number, first_number - second_number))
The difference between 4 and 3 is 7        

Do you see it?

The values of the first and third variables have been swapped in the final string.

This can also get a bit messy if you have lots of parameters to pass to the format method.

But, there is an even better way…

Using the Python Format Method with Keyword Arguments

The format() method also supports keyword arguments that make the code a lot more readable.

Let’s update the previous example that was using positional arguments. This time we will use keyword arguments instead.

>>> print("The difference between {fnum} and {snum} is {difference}".format(fnum=first_number, snum=second_number, difference=first_number - second_number))
The difference between 7 and 3 is 4         

I have assigned keywords to identify the parameters passed to the format method. And I have specified those keywords between curly braces.

A lot cleaner!

Also, I can swap the order in which the parameters are passed to the format method and the output will not change:

>>> print("The difference between {fnum} and {snum} is {difference}".format(snum=second_number, difference=first_number - second_number, fnum=first_number))
The difference between 7 and 3 is 4         

Conclusion

With this tutorial, you know pretty much anything you need to concatenate strings in Python.

My suggestion is to get used to the syntax of the format() method and it will make your code a lot cleaner.

Bonus read: in this article, you have learned how to concatenate strings in Python. To complement this knowledge have a look at how to split strings in Python. You will find it very useful in your Python programs!

Related course: build a strong Python foundation with this Python specialization.

Leave a Comment