Open In App

How to copy a string in Python

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a copy of a string is useful when we need a duplicate of a string to work with while keeping the original string intact, strings in Python are immutable which means they can't be altered after creation, so creating a copy sometimes becomes a necessity for specific use cases.

Using Slicing

Slicing ensures that a new object is created in memory. The slicing operator[:] creates a new string by extracting all characters from the original.

Python
original = "Hello, Python!"

# Create a copy using slicing
copy = original[:]
print(original)
print(copy)
print(original is copy)

Output
Hello, Python!
Hello, Python!
True

Let's explore some other ways to copy a string in python

Using Assignment

Another simple way to copy a string is by assigning it to a new variable. The copy variable points to the same memory location as original and both the variables reference the same string object.

Python
original = "Hello, Python!"

#Assign the original string to a new variable
copy = original
print(original)
print(copy)
print(original is copy)

Output
Hello, Python!
Hello, Python!
True

Using str() Constructor

The str() constructor explicitly creates a new string object with the same value from an existing one. str() ensures a new object is created, the new variable points to a different memory location

Python
original = "Python is fun!"

#Create a copy using str()
copy = str(original)
print(original)
print(copy)
print(original is copy)

Output
Python is fun!
Python is fun!
True


Next Article

Similar Reads