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.
1str1 = "Hello"
2str2 = "World"
3concatenated_str = str1 + " " + str2
4print(concatenated_str)
Output:
Hello World
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.
1str1 = "Hello"
2str2 = "Code"
3str3 = "Bay"
4concatenated_str = str1 + " " + str2 + " " + str3
5print(concatenated_str)
Output:
Hello Code Bay
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.
1str1 = "Hello "
2num = 5
3print(str1 + num)
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.
1str1 = "Hello "
2num = 5
3print(str1 + str(num))
Output:
Hello 5
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.