You don't need to copy a Python string. They are immutable, and the copy module always returns the original in such cases, as do str(), the whole string slice, and concatenating with an empty string.

Moreover, your 'hello' string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.

One way you could work around this is to actually create a new string, then slice that string back to the original content:

>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)

But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.

If all you wanted to know is how much memory a Python object requires, use sys.getsizeof(); it gives you the memory footprint of any Python object.

For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:

>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360

You can then choose to use id() tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.

Answer from Martijn Pieters on Stack Overflow
Top answer
1 of 8
202

You don't need to copy a Python string. They are immutable, and the copy module always returns the original in such cases, as do str(), the whole string slice, and concatenating with an empty string.

Moreover, your 'hello' string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.

One way you could work around this is to actually create a new string, then slice that string back to the original content:

>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)

But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.

If all you wanted to know is how much memory a Python object requires, use sys.getsizeof(); it gives you the memory footprint of any Python object.

For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:

>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360

You can then choose to use id() tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.

2 of 8
24

I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".

As long as a, b, c, d, and e have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:

import copy
a = 'hello'
b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)

print map( id, [ a,b,c,d,e ] )

print a, b, c, d, e

e = a + 'something'
a = 'goodbye'
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e

The printed output is:

[4538504992, 4538504992, 4538504992, 4538504992, 4538504992]

hello hello hello hello hello

[6113502048, 4538504992, 4538504992, 4538504992, 5570935808]

goodbye hello hello hello hello something
🌐
CodeScracker
codescracker.com › python › program › python-program-copy-string.htm
Python Program to Copy String
Indexing starts with 0. For example, if user enters a string say codes and this string gets initialized to a variable say sOne. That is, sOne = "codes". Then sOne[0] refers to "c" (first character of "codes"), sOne[1] refers to "o" (second character of "codes"), and so on · Therefore in similar way like done in previous program, this program also copies the string in character by character manner.
Discussions

Safest way to copy a string?
One option is snprintf(dest,n,“%s”,src), but this will likely be a little slower due to the time needed to parse the format string. More on reddit.com
🌐 r/C_Programming
79
55
May 7, 2023
Are there better ways to copy one string to another?
C doesn't really have a string data type that is something CS50 just made up to make the early weeks easier a string is actually a char * that's called a character pointer it does NOT hold a character it holds a memory address so this string str1 = "this is 26 characters12345"; string str2; actually means char *str1 = "this is 26 characters12345"; char *str2; which actually means your computer has 32 gigs or RAM (little blocks of memory numbered 1 to one billion) str1 does NOT contain the letter 't' str1 contains the number (address) to one of those blocks we have no idea what that number is --- it is automatically assigned by the compiler but let's say that number is 132 so if we went to memory block 132 we would fine the letter 't' and if we went to memory block 133 we would fine the letter 'h' and if we went to memory block 134 we would fine the letter 'i' and if we went to memory block 135 we would fine the letter 's' and so on str2 also contains the address of a block of memory that was automatically assigned to it if we were to go to that memory block what would we find ? who knows ??? what's going to be in there is what was in there after the computer booted up could be any random thing the point is that memory block does NOT belong to you neither does the memory right after it, neither does the next memory block, or the next, or the next ... so when you say str2[i] = str1[i]; what you're really saying is i = 0 so take what is at str1's memory block number + 0 and put it into the memory block at str2's memory block + 0 i = 1 so take what is at str1's memory block number + 1 and put it into the memory block at str2's memory block + 1 and the computer says "No, you don't own the memory block at str2" and then your program crashes but when you do char str2[26] and then do i = 0 so take what is at str1's memory block number + 0 and put it into the memory block at str2's memory block + 0 i = 1 so take what is at str1's memory block number + 1 and put it into the memory block at str2's memory block + 1 the computer says, no problem because you made space for str2, you own str2 and the 26 memory blocks after it More on reddit.com
🌐 r/cs50
5
3
September 16, 2022
Python copy.copy() appears to make a deep copy
The difference between a deep copy and a shallow copy is whether or not nested mutable structures are (recursively) copied (deep) or just referenced (shallow). All elements of your list are immutable. Therefore, there is no difference between a shallow and a deep copy. A proper demonstration of the difference is this: import copy my_list = [['first'], ['second'], ['third']] my_deep_copy = copy.deepcopy(my_list) my_deep_copy[1][0] = 'new value' print(my_list) my_shallow_copy = copy.copy(my_list) my_shallow_copy[1][0] = 'new value' print(my_list) Note how it requires nested mutable structures. More on reddit.com
🌐 r/learnpython
10
October 17, 2022
New to python strange copy string behavior
the length is the same for me: https://repl.it/@sharkbound/RepentantStimulatingUnderstanding i shorted the code a bit to show less console clutter. More on reddit.com
🌐 r/learnpython
25
4
October 12, 2018
🌐
W3Schools
w3schools.com › c › ref_string_strcpy.php
C string strcpy() Function
Note: Make sure that the destination string has enough space for the data or it may start writing into memory that belongs to other variables. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Cython
cython.readthedocs.io › en › latest › src › tutorial › strings.html
Unicode and passing strings — Cython 3.3.0a0 documentation
This creates a Python byte string object that holds a copy of the original C string. It can be safely passed around in Python code, and will be garbage collected when the last reference to it goes out of scope. It is important to remember that null bytes in the string act as terminator character, as generally known from C.
🌐
Quora
quora.com › How-do-you-create-a-copy-of-a-string-in-Python
How to create a copy of a string in Python - Quora
Answer (1 of 6): We can create a copy of a string in three ways, in Python. Let’s discuss this one by one. Screenshots will help you understand this easy! Let’s say I have a string “name” with some value: METHOD - 1: Assigning the value of original string to a new variable is the easiest optio...
🌐
Reddit
reddit.com › r/c_programming › safest way to copy a string?
r/C_Programming on Reddit: Safest way to copy a string?
May 7, 2023 -

I just fell foul of the fact that strncpy does not add an old terminator if the destination buffer is shorter than the source string. Is there a single function standard library replacement that I could drop in to the various places strncpy is used that would copy a null terminated string up to the length of the destination buffer, guaranteeing early (but correct) termination of the destination string, if the destination buffer is too short?

Edit:

  • Yes, I do need C-null terminated strings. This C API is called by something else that provides a buffer for me to copy into, with the expectation that it’s null terminated

Edit 2:

  • I know I can write a helper function that’s shared across relevant parts of the code, but I don’t want to do that because then each of those modules that need the function becomes coupled to a shared helper header file, which is fine in isolation but “oh I want to use this code in another project, better make sure I take all the misc dependencies” is best avoided. Necessary if necessary, but if possible using a standard function, even better.

🌐
Delft Stack
delftstack.com › home › howto › python › python copy string
How to Copy String in Python | Delft Stack
February 2, 2024 - We then create a new string nstr using string slicing, denoted by ostr[:], and this slicing notation extracts a copy of the entire original string, essentially duplicating its content. Finally, we print the resulting string nstr to the console. The output will be Web, representing the duplicated content of the initial string. The str() function in Python is a built-in function that converts an object into a string representation.
Find elsewhere
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.4 documentation
The string on which this method ... the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument....
🌐
W3Schools
w3schools.com › c › ref_string_strncpy.php
C string strncpy() Function
The strncpy() function copies the first n characters from one string into the memory of another string.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-copy-a-string-in-python
How to copy a string in Python - GeeksforGeeks
July 23, 2025 - Slicing ensures that a new object is created in memory. The slicing operator[:] creates a new string by extracting all characters from the original. ... original = "Hello, Python!" # Create a copy using slicing copy = original[:] print(original) print(copy) print(original is copy)
🌐
Medium
medium.com › @thecodeteacher › python-how-to-copy-string-c0f72cf99d02
Python — How To Copy String
January 26, 2022 - The following code uses slicing to copy a string in Python. ... The str() function, when made to pass a given string as its argument, returns the original string itself. This can be utilized when we have to create a copy string.
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › is it possible to copy string in python? [solved]
Is it possible to copy string in Python? [SOLVED] | GoLinuxCloud
January 9, 2024 - Slicing ([:]): Creates a new string by slicing the entire original string. This effectively produces a copy of the original string. str() Constructor: Creates a new string using Python's built-in str() constructor, resulting in a copy of the ...
🌐
Linux Hint
linuxhint.com › python-copy-string
Python Copy String
March 29, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Rosetta Code
rosettacode.org › wiki › Copy_a_string
Copy a string - Rosetta Code
4 weeks ago - LDA #<RamBuffer STA dest LDA #>RamBuffer STA dest_hi strcpy: ;assumes that RamBuffer is big enough to hold the source string, and that the memory ranges do not overlap. ;if you've ever wondered why C's strcpy is considered "unsafe", this is why. LDY #0 .again: LDA (source),y STA (dest),y BEQ .done INY BNE .again ;exit after 256 bytes copied or the null terminator is reached, whichever occurs first.
🌐
Jeremy Morgan
jeremymorgan.com › python › how-to-copy-a-string-in-python
How to Copy a String in Python - Jeremy Morgan's
December 10, 2023 - You can also copy a string by concatenating it with an empty string. This method creates a new string object that contains the same characters as the original string. For example: original_string = "Hello, World!" new_string = "" + original_string print(new_string) ... In addition to these basic methods, there are several advanced techniques for working with strings in Python...
🌐
CodeVsColor
codevscolor.com › how to copy string in python - codevscolor
How to copy string in python - CodeVsColor
September 1, 2021 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › function-copy-string-iterative-recursive
Function to copy string (Iterative and Recursive) - GeeksforGeeks
December 7, 2022 - DSA Python · Last Updated : 7 Dec, 2022 · Given two strings, copy one string to another using recursion. We basically need to write our own recursive version of strcpy in C/C++ Examples: Input : s1 = "hello" s2 = "geeksforgeeks" Output : s2 = "hello" Input : s1 = "geeksforgeeks" s2 = "" Output : s2 = "geeksforgeeks" Iterative: Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn't reach to end; Implementation: C++ // Iterative CPP Program to copy one String // to another.
🌐
Tutorial Gateway
tutorialgateway.org › python-program-to-copy-a-string
Python Program to Copy a String
December 19, 2024 - # Python Program to Copy a String str1 = input("Please Enter Your Own String : ") str2 = str1 str3 = str1[:] print("The Final String : Str2 = ", str2) print("The Final String : Str3 = = ", str3) ... Please Enter Your Own String : Hi Guys The Final String : Str2 = Hi Guys The Final String : Str3 = = Hi Guys · In this program, we are using For Loop to iterate each character in a string and copy them to the new string.
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_strncpy.htm
C library - strncpy() function
The C library strncpy() function accepts three parameters(dest, src, n) which copies up the n characters from the string pointed to, by src to dest. In this case, the length of src is less than that of n, the remainder of dest will be added with
🌐
Programiz
programiz.com › c-programming › library-function › string.h › strcpy
C strcpy() - C Standard Library
The strcpy() function also returns the copied string. The strcpy() function is defined in the string.h header file. #include <stdio.h> #include <string.h> int main() { char str1[20] = "C programming"; char str2[20]; // copying str1 to str2 strcpy(str2, str1); puts(str2); // C programming return 0; }