In Python, you can concatenate two different strings together and also the same string to itself multiple times using +
and the *
operator respectively.
+
operatorThe +
operator can be used to concatenate two different strings.
The following illustration shows how it is done:
str1="Hello" str2="World" print ("String 1:",str1) print ("String 2:",str2) str=str1+str2 print("Concatenated two different strings:",str)
*
operatorAppending the same string to a string can be done using the *
operator, as follows:
str=str * x
str
is appended to itself.The following illustration shows how it is done:
str1="Hello" print ("String 1:",str1) str1=str1*3 print("Concatenated same string:",str1)
Note: When concatenating a variable of non-string type with a string, you first need to cast that variable into a string.
RELATED TAGS
View all Courses