Add one Python string to another


By adding strings in python we just concatenate them to get a new string. This is useful in many scenarios like text analytics etc. Below are the two approaches we consider for this task.

Using += Operator

The + operator can be used for strings in a similar was as it is for numbers. The only difference being, in case of strings the concatenation happens and not a numeric addition.

Example

 Live Demo

s1 = "What a beautiful "
s2 = "flower "

print("Given string s1 : " + str(s1))
print("Given string s2 : " + str(s2))
#Using += operator
res1 = s1+s2
print("result after adding one string to another is : ", res1)

# Treating numbers as strings
s3 = '54'
s4 = '02'
print("Given string s1 : " + str(s3))
print("Given string s2 : " + str(s4))
res2 = s3+s4
print("result after adding one string to another is : ", res2)

Output

Running the above code gives us the following result −

Given string s1 : What a beautiful
Given string s2 : flower
result after adding one string to another is : What a beautiful flower
Given string s1 : 54
Given string s2 : 02
result after adding one string to another is : 5402

Using join

We can use the join() in a similar manner as the plus operator above. We can join any number of strings using this method. The result will be same as the plus operator.

Example

 Live Demo

s1 = "What a beautiful "
s2 = "flower "

print("Given string s1 : " + str(s1))
print("Given string s2 : " + str(s2))
print("result after adding one string to another is : "," ".join((s1,s2)))

# Treating numbers as strings
s3 = '54'
s4 = '02'
print("Given string s1 : " + str(s3))
print("Given string s2 : " + str(s4))
print("result after adding one string to another is : ","".join((s3,s4)))

Output

Running the above code gives us the following result −

Given string s1 : What a beautiful
Given string s2 : flower
result after adding one string to another is : What a beautiful flower
Given string s1 : 54
Given string s2 : 02
result after adding one string to another is : 5402

Updated on: 18-Feb-2020

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements