How to Concatenate Strings (Not Integers) in Python?

Estimated read time 2 min read

To concatenate strings in Python, you can use the + operator or the str.join() method. Here’s how you can use each method:

  1. Using the + operator: You can concatenate two or more strings using the + operator. Here’s an example:
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str)  # Output: Hello World

In this example, we concatenate the strings str1 and str2 along with a space in between.

  1. Using the str.join() method: The str.join() method allows you to concatenate multiple strings from a list or iterable. Here’s an example:
words = ["Hello", "World"]
concatenated_str = " ".join(words)
print(concatenated_str)  # Output: Hello World

In this example, we use the join() method to concatenate the strings from the words list with a space in between.

The join() method takes an iterable (e.g., a list) of strings as its argument and returns a single string by concatenating them with the specified separator.

You can use either method based on your specific needs. The + operator is useful for concatenating a small number of strings, while the str.join() method is more efficient for concatenating a larger number of strings from an iterable.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply