Concatenating two strings refers to the merging of both the strings together. Concatenation of “Tutorials” and “Point” will result in “TutorialsPoint”.
We will be discussing different methods of concatenating two strings in Python.
Using ‘+’ operator
Two strings can be concatenated in Python by simply using the ‘+’ operator between them.
More than two strings can be concatenated using ‘+’ operator.
Example
s1="Tutorials" s2="Point" s3=s1+s2 s4=s1+" "+s2 print(s3) print(s4)
Output
TutorialsPoint Tutorials Point
Using % operator
We can use the % operator to combine two string in Python. Its implementation is shown in the below example.
Example
s1="Tutorials" s2="Point" s3="%s %s"%(s1,s2) s4="%s%s"%(s1,s2) print(s3) print(s4)
Output
Tutorials Point TutorialsPoint
The %s denotes string data type. The space between the two strings in the output depends on the space between “%s %s”, which is clear from the example above.
Using join() method
The join() is a string method that is used to join a sequence of elements. This method can be used to combine two strings.
Example
s1="Tutorials" s2="Point" s3="".join([s1,s2]) s4=" ".join([s1,s2]) print(s3) print(s4)
Output
TutorialsPoint Tutorials Point
Using format()
The format() is a string formatting function. It can be used to concatenate two strings.
Example
s1="Tutorials" s2="Point" s3="{}{}".format(s1,s2) s4="{} {}".format(s1,s2) print(s3) print(s4)
Output
TutorialsPoint Tutorials Point
The {} set the position of the string variables. The space between the ‘{} {}’ is responsible for the space between the two concatenated strings in the output.