How to concatenate two strings in Python
In this tutorial, we will learn how to concatenate two strings in Python. There are different ways of string concatenation. Let’s explore one by one.
Strings are a collection of characters inside single quotes or double-quotes. Strings have immutability property, i.e. we cannot mutate the string but the value of a variable can be changed to a new string.
You may learn: how to escape quotes in Python
Concatenation of two string in Python
Two or more strings can be combined and the process is known as string concatenation. Take two strings, merge them and they will become one.
For example, let the first string be “Code” and the other be “Speedy“. After concatenation, they will become “Code Speedy“.
There are several ways by which we can concatenate strings in Python.
Using ‘+’ operator: Concatenate strings in Python
"First String"+"Second string"
'First stringSecond String'
- If we want to add space between the strings, then write your code as follows:
Add space in between two strings while concatenating two strings in Python
"Welcome to " + "Codespeedy"
'Welcome to Codespeedy'
- Another method for giving space:
"Welcome to" + ' ' + "Codespeedy"
'Welcome to Codespeedy'
Or the strings can be assigned to variables and then concatenated:
a = "Welcome to" b = "Codespeedy" c = ' ' d = a+c+b print(d)
'Welcome to Codespeedy'
- We cannot add an integer to a string.
TypeError: can only concatenate str (not “int”) to str
a = "Hello" a+9
Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> a+9 TypeError: can only concatenate str (not "int") to str
We need to convert the integer to string using str().
a+str(9)
'Hello9'
- To print a single string multiple times:
print("Rose"*4)
RoseRoseRoseRose
Leave a Reply