How To Copy A String In Python

In this tutorial, you will learn how to copy a string in Python using different methods. We’ll discuss how to make an exact copy of a string, create a new string from the original, and concatenate multiple strings together.

Step 1: Assigning a String to a New Variable

The most straightforward way to copy a string is simply by assigning it to another variable. This creates a new reference to the original string. Here’s how to do it:

However, keep in mind that this does not create a new string object. Both original_string and copied_string are references to the same string in memory. For most use cases, this method is sufficient and efficient.

Step 2: Using the Slice Operator to Copy a String

Another method for creating a true copy of a string is to use the slice operator ([:] or [::1]). This method creates a new string object by slicing the original string.

or

Both of these examples create a new string, copied_string, containing the same characters as original_string. Unlike the previous method, this creates a new string object in memory.

Step 3: Using the str() Function to Copy a String

You can also create a copy of a string using Python’s built-in str() function. This function returns a string that is either a copy of the original string or a new string from any object that can be converted to a string.

In this example, we copy the original_string into a new string object called copied_string.

Step 4: Using the String join() Method

Another way to copy a string is to use the join() method. This method allows you to concatenate a sequence of strings using a specified delimiter. For this purpose, we can use an empty delimiter to create a copy of the original string.

In this example, we join each character from original_string with an empty delimiter, creating a new copy of the string in copied_string.

Full Code

Output

Original string: Hello, World!
Copied strings:
Method 1: Hello, World!
Method 2: Hello, World!
Method 3: Hello, World!
Method 4: Hello, World!
Method 5: Hello, World!

Conclusion

In this tutorial, you’ve learned four methods for copying a string in Python: assigning to a new variable, using the slice operator, employing the str() function, and using the join() method. These options can be helpful in different situations, depending on whether you need a new reference to the original string, a new string object with the same content, or the ability to concatenate strings together.