Concatenation
What is String Concatenation?
String concatenation is the operation of joining two or more string values end-to-end. In Python, you can join strings with the ‘+’ operator. It doesn’t add like numerical values but glues the strings together, forming a more extended string.
Output:
The function print() displays the result on the console: “Hello World”. It’s because the string variables str1 and str2 were concatenated, with an additional string containing just a space " " in the middle.
Joining Multiple Strings
It’s also possible to join or concatenate multiple strings at once.
Output:
Notice how each string is separated by a " " in the console.
Concatenation with Other Data Types
Be cautious when trying to concatenate strings with other data types. Python doesn’t support the concatenation of strings with non-strings. For example, trying to concatenate a string with a number will result in a TypeError.
The code snippet above will result in TypeError: can only concatenate str (not “int”) to str.
To concatenate a number to a string, the number must be converted into a string first with the str() function.
Output:
Now the number 5 was successfully concatenated to the “Hello " string after being converted to a string.
Did you know?
String concatenation is a common operation in Python programming, especially when dealing with user input, file reading/writing, and generating output.