String concatenation is the process of joining two or more strings end-to-end to form a new, combined string. In Python, concatenation combines text values to create readable messages, dynamic output, or formatted strings.
How to Concatenate Strings Using + Operator
The most common way to concatenate strings in Python is with the + operator. This operator takes two or more string values and returns a new string containing their text one after another.
Example:
Here, first + second joins "Hello" with "World" to create "HelloWorld". Because strings are immutable, this creates a new string.
Adding Space Between Strings
To insert a space or other character between concatenated strings, include it as part of the concatenation:
The literal " " adds a space between the text segments.
Concatenating Variables with Text
You can concatenate string variables with text content to build messages or dynamic output.
This generates a new string by combining text with the variable value.
Using += for Concatenation
You can also use augmented assignment (+=) to update a variable with additional text. Internally, this creates a new string and reassigns the variable.
This performs the same concatenation as text = text + " rocks".
Important Notes About Concatenation
-
Python creates a new string for each concatenation because strings are immutable. ([turn0search8])
-
If you repeatedly concatenate many strings (especially in loops), it may be less efficient than other techniques because each operation builds a new string object. ([turn0search8][turn0search9])
-
Concatenation works only with string data types; combining a string with a number without conversion causes an error.