String concatenation is a common task in most applications. In this article, we will look into different ways to concatenate strings in Python.
1.Using the + operator
To concatenate strings we can use the + operator.
str1 = "Happy"
str2 = "Coding"
result = str1 + str2
print(result)
Output
HappyCoding
Here string str1 and str2 are joined using the + operator. We can add space between str1 and str2 as shown below.
str1 = "Happy"
str2 = "Coding"
result = str1 + " " + str2
print(result)
Output
Happy Coding
2.Using the string join() method
We can join strings using the join method. The join method returns a string by joining all the elements of iterable (string, list, tuple) separated by a string separator.
str1 = "Happy"
str2 = "Coding"
result = " ".join([str1,str2])
print(result)
Here we converted str1 and str2 into list [str1,str2] and separator is space (” “). The join method will combine str1 and str2 strings, separated by space.
Output
Happy Coding
3.Using the string formatting % operator
We can join strings using the string formatting % operator as shown below.
str1 = "Happy"
str2 = "Coding"
result = "%s %s" % (str1,str2)
print(result)
Here %s (format specifier for string) is replaced by the corresponding strings (str1 and str2).
Output
Happy Coding
4. Using the string formatting { } operator
We can join the strings using the {} operator. When we use string format function with curly braces or {} it act as a placeholder for the variables.
str1 = "Happy"
str2 = "Coding"
result = "{} {}".format(str1,str2)
print(result)
Output
Happy Coding
5. Join the same string the * operator
And finally, we will look into * operator. Using this operator we can repeat string n times.
result = string * n #n= number of times
Let’s look into an example
str1 = "Happy"
result = str1 * 3
print(result)
We can see that result has the value “HappyHappyHappy”, str1 is repeated 3 times.
Output
HappyHappyHappy
Conclusion
There you have it, different ways to concatenate strings in Python.