This operator can be used to perform this particular task of concatenating the string. This is quite simpler than the traditional methods that are employed in other languages, like using a dedicated function to perform this particular task.
# initializing string
test_string = "GFG"
# initializing add_string
add_string = " is best"
# printing original string
print("The original string : " + str(test_string))
# printing original add string
print("The add string : " + str(add_string))
# Using += operator
# adding one string to another
test_string += add_string
Output :
The original string : GFG The add string : is best The concatenated string is : GFG is best
One can also perform this very task of the concatenation of strings using the Python join function. The advantage this method holds over the above method is when we have many strings to concatenate rather than just two.
# initializing string
test_string = "GFG"
# initializing add_string
add_string = " is best"
# printing original string
print("The original string : " + str(test_string))
# printing original add string
print("The add string : " + str(add_string))
# Using join()
# adding one string to another
res = "".join((test_string, add_string))
Output:
The original string : GFG The add string : is best The concatenated string is : GFG is best
In this example, we are adding a string to another string using the Python f-string.
# initializing string
test_string = "GFG"
# initializing add_string
add_string = " is best"
# printing original string
print("The original string : " + str(test_string))
# printing original add string
print("The add string : " + str(add_string))
# Using f-string
# adding one string to another
res = f'{test_string}{add_string}'
Output:
The original string : GFG The add string : is best The concatenated string is : GFG is best
In this example, we are adding a string to another string using the Python __add__ method.
# initializing string
test_string = "programmingshark"
# initializing add_string
add_string = " is best"
# printing original string
print("The original string : " + str(test_string))
# printing original add string
print("The add string : " + str(add_string))
# Using __add__
# adding one string to another
res = test_string.__add__(add_string)
Output:
The original string : programmingshark The add string : is best The concatenated string is : Geeksforgeeks is best
In this example, we are adding a string to another string using the Python format() function.
# initializing string
test_string = "programmingshark"
# initializing add_string
add_string = " is best"
# printing original string
print("The original string : " + str(test_string))
# printing original add string
print("The add string : " + str(add_string))
# Using format
# adding one string to another
res = "{}{}".format(test_string, add_string)
Output:
The original string : programmingshark The add string : is best The concatenated string is : Geeksforgeeks is best