How to concatenate two strings in Python?

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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

 Live Demo

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

 Live Demo

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.

raja
Published on 10-Mar-2021 14:11:00
Advertisements