3 methods to append to the end of a string in Python

3 methods to append to the end of a string in Python

In this tutorial, we'll be learning three methods to append to the end of a string.

Append to the end of the string using the (+) operator

With the + operator, we can concatenate two strings or more. In the following example, we'll see how to append a string to the end of another string.

my_str = "Hello"

# Append to the end of a string using (+)
print(my_str + " Python")

Output:

Hello Python

As you can see, we've appended the word Python to my_str.

Now, we have a list of items, and we want to append them to the end of a string. In the following example, we'll see how.

# String
my_str = "Hello"

# List of items
my_list = ["Python", "Django", "Flask", "Bottle"]

for i in my_list:
    # Append the items to the end of my_str
    my_str += i

# Print my_str
print(my_str)

Output:

HelloPythonDjangoFlaskBottle

We have used the += operator to add my_list items to my_str. It is equivalent to:
my_str = my_str + items of my_list.

Append to the end of a string using the f-string

f-string is a new string formatting available on Python 3.6 or above.

We can use an f-string to append a value to the end of a string.

Example:

# String
my_str = "Hello"

# Append to the end of string using f-string
print(f"{my_str} Python")

Output:

Hello Python

As demonstrated, we've appended Python to my_str.

Append to the end of a string using the format function

The format function is the old version of the f-string. This function is available on all Python versions.

Let's see how to use it with an example.

# String
my_str = "Hello"

# Append to the end of string using format()
print("{} {}".format(my_str, "Python"))

Output:

Hello Python