How do I concatenate strings in Python?
Antek N
antek n profile pic

In Python, there are several ways to concatenate strings. Here's a detailed explanation of some commonly used methods: 1. Using the+ operator: You can use the+ operator to concatenate strings together.

1
2
3
4
5
6
7

str1 = "Hello"
str2 = "World"

concatenated = str1 + " " + str2

print(concatenated)  # Output: "Hello World"

2. Using thestr.join() method: Thestr.join() method allows you to concatenate a list of strings by specifying a separator. It is particularly useful when you have a list of strings to concatenate.

1
2
3
4
5
6

words = ["Hello", "World"]

concatenated = " ".join(words)

print(concatenated)  # Output: "Hello World"

3. Using f-strings (formatted strings): Introduced in Python 3.6, f-strings provide a concise way to concatenate strings by embedding expressions inside curly braces{} within the string. The expressions are evaluated and their values are inserted into the resulting string.

1
2
3
4
5
6
7

str1 = "Hello"
str2 = "World"

concatenated = f"{str1} {str2}"

print(concatenated)  # Output: "Hello World"

4. Using the+= operator: You can use the+= operator to append strings to an existing string.

1
2
3
4
5
6
7

str1 = "Hello"
str2 = "World"

str1 += " " + str2

print(str1)  # Output: "Hello World"

5. Using thestr.format() method: Thestr.format() method allows you to concatenate strings by substituting placeholders{} with corresponding values.

1
2
3
4
5
6
7

str1 = "Hello"
str2 = "World"

concatenated = "{} {}".format(str1, str2)

print(concatenated)  # Output: "Hello World"

These are some of the commonly used methods to concatenate strings in Python. Choose the method that best suits your needs, taking into consideration factors such as readability, performance, and the specific requirements of your program.