How To Append to Strings in Python?

Posted in Python by Dirk - last update: Dec 19, 2023

In Python, strings are immutable, meaning you cannot directly modify the contents of a string once it is created. However, you can create a new string by concatenating the existing string with the new content. There are several ways to append to a string in Python

Using the + operator

In Python, the easiest way to append to a string is by using the ‘+’ operator. With ‘+’ you append the content of the second string to the first: ‘a’+‘b’ becomes ‘ab’. While simple, it’s not always the recommended way to append to a string. If you have a large number of string concatenations, especially in a loop, join() is more efficient.

original_string = "Hello, "
new_content = "world!"

concatenated_string = original_string + new_content
print(concatenated_string)

Output:

Hello world!

Using the += operator

This method is almost identical to the previous one - it’s bitter shorter to write.

original_string = "Hello, "
new_content = "world!"
original_string += new_content
print(original_string)

Output

Hello world!

Using the join method:

The join() method in Python is a string method that is used to concatenate a list of strings into a single string. It takes an iterable (e.g., a list, tuple, or string) as its argument and joins the elements of the iterable by a specified string (the string on which the method is called).

If we want to append concatenate two strings it looks like this:

original_string = "Hello, "
new_content = "world!"
concatenated_string = ''.join([original_string, new_content])
print(concatenated_string)

This method is particularly useful when you have a list of strings that you want to concatenate efficiently. It is more efficient than using the + operator for concatenating strings in a loop because it avoids creating intermediate string objects.

Using f-strings (Python 3.6 and above)

An f-string, also known as a formatted string literal, is a way to embed expressions inside string literals in Python. F-strings are introduced by the prefix “f” or “F” and are available in Python 3.6 and later versions. They provide a concise and readable way to include the values of variables or expressions directly within string literals.

They can however also be used to append a string to a string: Example:

original_string = "Hello, "
new_content = "world!"

concatenated_string = f"{original_string}{new_content}"

print(concatenated_string)

In an f-string:

  • The curly braces {} are used to enclose expressions.
  • The expressions inside the curly braces are evaluated at runtime.
  • The resulting values are then formatted and inserted into the string.

In the example above - we take an empty string "" and we include the texts that needs to be concatenated by adding the variables within the curly braces {} On runtime - {original_string} becomes Hello, and {new_content} becomes world! - with f-string this becomes “Hello, world!”

Using format()

You can use the format() method for string formatting and appending. Here’s an example:

item1 = "apple"
item2 = "orange"
item3 = "banana"
shopping_list = "Shopping list: {}, {}, and {}.".format(item1, item2, item3)
print(shopping_list)

Output:

Shopping list: apple, orange, and banana.

The format() method provides a flexible way to format strings with placeholders. You can also use named placeholders and various formatting options to control the appearance of the final string. This method is especially useful when you need more complex formatting or want to keep your code compatible with Python 2 (as f-strings are available only in Python 3.6 and later).

Remember that starting from Python 3.6, f-strings provide a more concise and often more readable way to achieve the same result (see example above)

Potential risks

Memory

Since strings are immutable, each concatenation operation creates a new string, potentially leading to increased memory usage. If memory efficiency is critical, consider alternative data structures like lists. Prefer .join() over + or +=

Handle None or non-string values

Make sure that the values you are appending are of the expected type (string). If you are unsure about the content, handle potential None values and/or convert non-string values to strings before appending.

An example:

result = "prefix"
value = get_some_value()
if value is not None:
    result += str(value)

First - the if statements checks that the value is not None. The str() function converts the value to string, regardless of its initial type.

Other articles