How to Join Strings in Python

09/11/2021

Contents

In this article, you will learn how to join strings in Python.

How to join strings in Python

In Python, there are several ways to join strings together. Here are some of the most common methods:

Using the plus (+) operator

You can join two or more strings using the plus (+) operator.

For example:

string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result)  # Output: "Hello World"

Using the join() method

The join() method is used to join a sequence of strings. It takes a separator string and a sequence of strings as arguments. The separator is inserted between each pair of strings in the sequence.

For example:

mylist = ["apple", "banana", "cherry"]
separator = ", "
result = separator.join(mylist)
print(result)  # Output: "apple, banana, cherry"

Using f-strings

f-strings are a convenient way to format strings in Python. You can use them to join strings together by including the variables you want to join in a formatted string.

For example:

string1 = "Hello"
string2 = "World"
result = f"{string1} {string2}"
print(result)  # Output: "Hello World"

Using the format() method

You can use the format() method to insert variables into a string and join multiple strings together.

For example:

string1 = "Hello"
string2 = "World"
result = "{} {}".format(string1, string2)
print(result)  # Output: "Hello World"

Using the % operator

Another way to format and join strings in Python is to use the % operator. This method is similar to the format() method, but uses a different syntax.

Here’s an example:

string1 = "Hello"
string2 = "World"
result = "%s %s" % (string1, string2)
print(result)  # Output: "Hello World"