Skip to content

How to concatenate strings in Python?

Python is the language of choice for many programmers, especially those who are new to the programming world due to its simple syntax and easy to understand concepts.

All basic tasks in Python are rather easy to do, including operations on strings. In this article, we’re going over a few ways you can concatenate strings in Python. 

Also read: What is the difference between Python 2 and Python 3?


What is concatenation?

In layman terms, concatenation is the joining of two separate strings, There are four ways you can concatenate strings in Python. 

  • Using the + operator.
  • Using the operator.
  • Using the format() operator. 
  • Using the join() function.

Using the + operator

The operator can be used to add multiple strings together. The arguments, however, must be a string. Another thing to keep in mind is that since strings are immutable, you must assign them to a new variable every time you concatenate a string. 

Take a look at the example below.

str1 = "Candid"
str2 = "Technology"

str3 = str1 +" ." + str2

print(str3)

The output of the above snippet would be Candid.Technology


Using the % operator

The operator is generally used for string formatting, however, you can use it to concatenate strings as well. 

var1 = "Candid"
var2 = "Technology"

print("% s % s" % (var1, var2))

The above snippet will produce the following output Candid Technology. 

Also read: How to install Python on Windows?


Using join() function

The join() function is a string function that returns a concatenated string from the arguments that you provide. The elements of the sequence get joined together by the str seperator. 

var1 = "Candid"
var2 = "Technology"

print("".join([var1, var2]))

var3 = ".".join([var1, var2])

print(var3)

In the example above, the double quotes preceding the join method act as the separator between the two arguments. The output of the above snippet would be as follows.

CandidTechnology
Candid.Technology

Using the format() function

One of the most common formatting methods used in Python is str.format() . The method allows multiple substitutions and value formatting. However, you can use the function to concatenate elements within a string using position formatting. 

var1 = "Candid"
var2 = "Technology"

var3 = "{}.{}".format(var1, var2)

print(var3)

The output of the aforementioned snippet would simply be Candid.Technology. The first curly brackets will contain the first string, while the second curly brackets contain the string that’ll go later. 

Also read: How to use the Python range() function?

Hello There!

If you like what you read, please support our publication by sharing it with your friends, family and colleagues. We're an ad-supported publication. So, if you're running an Adblocker, we humbly request you to whitelist us.

We may earn a commission if you buy something from a link on this page. Thanks for your support.







>