Python Strings : Concatenate Strings
In Python, concatenating strings is a common operation. You can combine multiple strings using several techniques. Here are some ways to concatenate strings:
1. Using the + Operator
The simplest way to concatenate strings is by using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Adds a space between the strings
print(result) # Output: "Hello World"
2. Using join()
The join() method is useful when you have a list or tuple of strings and want to concatenate them into one string.
words = ["Hello", "World", "Python"]
result = " ".join(words) # Adds a space between each word
print(result) # Output: "Hello World Python"
3. Using format() Method
The format() method allows you to insert strings or variables into placeholders within a string.
str1 = "Hello"
str2 = "World"
result = "{} {}".format(str1, str2)
print(result) # Output: "Hello World"
4. Using f-Strings (Formatted String Literals)
Python 3.6+ allows string concatenation with f-strings, which is a clean and efficient way to format strings.
str1 = "Hello"
str2 = "World"
result = f"{str1} {str2}"
print(result) # Output: "Hello World"
5. Using % Operator
The % operator is another way to format strings.
str1 = "Hello"
str2 = "World"
result = "%s %s" % (str1, str2)
print(result) # Output: "Hello World"
6. Concatenating with * (for repetition)
You can use the * operator to concatenate the same string multiple times.
str1 = "Hello"
result = str1 * 3
print(result) # Output: "HelloHelloHello"
7. Concatenation in Loops
If you need to concatenate strings in a loop, it’s more efficient to use the join() method instead of + because + creates a new string every time, which can be slow for large strings.
words = ["Hello", "World", "Python"]
result = ""
for word in words:
result += word + " "
print(result.strip()) # Output: "Hello World Python"