Table of Contents
ToggleString concatenation in Python is the operation of joining two or more strings together. The result of this operation is a new string that contains the original strings. In this guide, we will explore various methods to concatenate strings in Python.
Python provides multiple ways to concatenate strings. Below are the most common methods:
The + operator is the most straightforward way to concatenate strings. It appends the characters of the string on the right to the string on the left.
str1 = "Hello"
str2 = "World"
print("String 1:", str1)
print("String 2:", str2)
str3 = str1 + str2
print("String 3:", str3)
Output:
String 1: Hello
String 2: World
String 3: HelloWorld
To insert a whitespace between two strings, you can use a third empty string or include the space directly in the concatenation.
str1 = "Hello"
str2 = "World"
blank = " "
print("String 1:", str1)
print("String 2:", str2)
str3 = str1 + blank + str2
print("String 3:", str3)
Output:
String 1: Hello
String 2: World
String 3: Hello World
The * operator can be used to repeat a string multiple times. One operand must be a string, and the other must be an integer specifying the number of repetitions.
newString = "Hello" * 3
print(newString)
Output:
HelloHelloHello
You can use both the + and * operators in a single expression to concatenate strings. The * operator has higher precedence than the + operator.
str1 = "Hello"
str2 = "World"
print("String 1:", str1)
print("String 2:", str2)
str3 = str1 + str2 * 3
print("String 3:", str3)
str4 = (str1 + str2) * 3
print("String 4:", str4)
Output:
String 1: Hello
String 2: World
String 3: HelloWorldWorldWorld
String 4: HelloWorldHelloWorldHelloWorld
In the first case, Python concatenates 3 copies of str2 first and then appends the result to str1. In the second case, the strings str1 and str2 are concatenated first, and the result is repeated 3 times.
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now