How to copy string in python

How to copy a string in python:

We have different ways to copy a string in python. String is immutable. If we directly assign the value of a string variable to another string variable, it will not copy that value to that new variable. Both will point to the same string.

Since string is immutable, we can get a new copy of the string by adding an empty string to the original string. Also we can slice the whole string or use str() function to get a copy of a string. Let’s try each of these methods:

By adding an empty string to the original string:

It is easy. We can add one empty string to the original string to get the required copy string as like below:

given_str = 'hello'
new_str = '' + given_str

print(new_str)

It will print hello as the output.

By slicing the string:

By slicing the string using the slice operator, we can get a new string. Slicing can be done in the range of a start and end index. If we don’t pass any start and end index, it will return the whole string or a copy of the original string.

Below example shows how it works:

given_str = 'hello'
new_str = given_str[:]

print(new_str)

It will print hello.

By using str():

We can pass one string to str() function and it will return one copy of that string.

given_str = 'hello'
new_str = str(given_str)

print(new_str)

It will print the same output.

Combining all:

Let’s write down all methods in one script:

given_str = 'hello'

new_str1 = '' + given_str
new_str2 = given_str[:]
new_str3 = str(given_str)

print('new_str1 : {}, new_str2 : {}, new_str3 : {}'.format(
    new_str1, new_str2, new_str3))

It will print:

new_str1 : hello, new_str2 : hello, new_str3 : hello

python string copy example

You might also like: