Python allows for the use of the addition (+) operator and multiplication (*) operator on strings.
In this tutorial, we’ll see how to use these operators with string in Python.
Addition(+) operator with string
Adding two strings is known as concatenation.
Concatenation of two strings creates a string by adding the second string to the end of first string.
str1='Hello' str2='World' print(str1+str2)
Output
HelloWorld
Please note that both the arguments to concatenate strings should be of string data type, else we’ll get TypeError.
str1='Hello' str2=5 print(str1+str2)
Output
TypeError: can only concatenate str (not "int") to str
Multiplication(*) operator with String
Multiplication operator is used with strings in Python for the purpose of repetition.
Multiplication operator when used with string in Python creates new strings by concatenating multiple copies of the same string.
print('Hello' * 5)
Output
HelloHelloHelloHelloHello
Please note that one of the values should be ‘int’, else we’ll get error.
TypeError: can't multiply sequence by non-int of type 'str'