How to Concatenate Strings in Python?

Estimated read time 2 min read

In Python, you can concatenate strings using the + operator or the join() method. Here’s how you can do it:

Using the + operator:

str1 = "Hello"
str2 = "World"
concatenated_string = str1 + " " + str2
print(concatenated_string)  # Output: "Hello World"

In this example, the + operator is used to concatenate the strings str1 and str2, along with a space character in between. The resulting concatenated string is assigned to the concatenated_string variable and printed.

Using the join() method:

strings = ["Hello", "World"]
concatenated_string = " ".join(strings)
print(concatenated_string)  # Output: "Hello World"

In this example, the join() method is called on a string with the separator ” ” (space) and the list of strings strings as the argument. The method concatenates all the strings in the list with the specified separator in between. The resulting concatenated string is assigned to the concatenated_string variable and printed.

Both approaches achieve the same result of concatenating strings. The choice between them depends on the specific requirements and preferences of your code. The join() method is particularly useful when you have a list of strings to concatenate, as it can handle variable-length lists more efficiently.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply