How to Concatenate Strings in Python
The process of string concatenation is the joining of one or more strings together to form a new string.
In Python, use the +
(addition) operator to add separate strings and the *
(multiplication) operator to multiply the same string.
Concatenate Different Strings
In the example below we are joining three different strings together to form a new string which is then assigned to a variable.
string_1 = 'Beginning '
string_2 = ' middle '
string_3 = ' end.'
result = string_1 + string_2 + string_3
print(result)
Beginning middle end.
Concatenate String X Multiples of Time
As mentioned at the beginning, you can use the *
(multiplication) operator to append a string to itself X multiples of time.
string_1 = 'hello '
string_1 = string_1 * 3
print(string_1)
hello hello hello
Concatenate Strings and Numbers
If you have a non-string that you need to concatenate to a string, you will need to convert it to a string first using type casting like this:
string_1 = 'hello '
num = 3
result = string_1 + str(num)
print(result)
hello 3