Concatenation is the process of combining two or more strings into a single string. In Python, you can concatenate strings using the + operator, like this:
str1 = "Hello"str2 = "world"str3 = str1 + " " + str2print(str3) # Output: "Hello world" |
In this example, we create two strings str1 and str2, and then concatenate them using the + operator. We also add a space between the two strings by including a space character inside double quotes. The resulting string is stored in a new variable str3, which is then printed to the console.
You can also use the += operator to concatenate strings, like this:
str1 = "Hello"str1 += " world"print(str1) # Output: "Hello world" |
In this example, we start with the string str1 and then concatenate the string " world" to it using the += operator. This appends the new string to the end of the existing string, and the resulting string is stored back in str1.
Note that you can only concatenate strings together, not other data types such as integers or floats. If you need to concatenate a string with a numeric value, you can use the str() function to convert the value to a string first, like this:
num = 42str1 = "The answer is " + str(num)print(str1) # Output: "The answer is 42" |
In this example, we convert the integer num to a string using the str() function, and then concatenate it with another string to produce the final result.