Quick Reach
String concatenation in Python
In Python, strings can be concatenated by using the + operator. Following are a few examples of Python string concatenation.
Python Concatenation example
Following example simply joins two sentences and displays it.
1 | print (“This is python tutorial” + ” This is concatenation chapter”) |
String concatenation of two variables
In the following example of Python string concatenation, we will use two string variables and combine those by using the ‘+’ operator. See the code with output!
1 2 3 4 5 | str1 = “This is Python Tutorial.” str2 = “This is concatenation chapter” print (str1 + ” “ + str2) |
The output will be:
This is Python Tutorial. This is concatenation chapter
What happens if Int is concatenated?
If an Int is tried to concatenate with string then an error will be generated.
1 2 3 4 5 6 7 | str1 = “This is Python Tutorial.” str2 = “This is concatenation chapter” int1 = 123 print (str1 + ” “ + int1) |
This will be output with an error message:
Traceback (most recent call last):
File “C:PythonProgramsshell.py”, line 4, in <module>
print (str1 + ” ” + int1)
TypeError: Can’t convert ‘int’ object to str implicitly
You have to convert an int to the string by using the Python str method in order to concatenate this. See example below:
1 2 3 4 5 6 7 | str1 = “This is Python Tutorial.” str2 = “This is concatenation chapter” int1 = 123 print (str1 + ” “ + str(int1)) |
The output will be:
This is Python Tutorial. 123
Also see – String length | Python Tuple
Leave A Comment?