Last updated on February 20, 2023
Combining two strings or two variables is called concatenation. Each programming language has a different way to concatenate the strings.
In python, the ‘+’ operator is used to concatenate two strings. Let’s Suppose, to concatenate “Hello” and “World”, you need to use the ‘+’ operator in between.
Below is an example
“Hello” + “World”
print(“Hello” + “World”)
# Output: HelloWorld
The output of the above concatenation will be HelloWorld
. If you notice, there is no space between both words. It is because both strings do not have any space. To add the space between the word, you can add the space at the end of the first word, look at the below example,
print("Hello " + "World")
# Output: Hello World
Another way is to add the space, you can concatenate a string containing space between the two values with the + operator.
print("Hello" + " " + "World")
# Output: Hello World
If the variable data type is a string, it can be concatenated by simply adding the ‘+’ operator between both variables, the same as strings. Below is an example
a = "Hello "
b = "World"
print(a + b)
# Output: Hello World
But if you change a variable’s data type, you will get TypeError. See below example
a = "Hello "
b = 1
print(a + b)
# Output: TypeError: can only concatenate str (not "int") to str
To fix the error (TypeError: can only concatenate str (not “int”) to str), you need to make sure that both variables have string values.
In python, you can concatenate two strings by using the ‘+’ operator. This article demonstrates in detail how can you concatenate strings.