Copy a string: Difference between revisions

Content added Content deleted
(→‎[[Python]]: Corrected "actual copy" code which doesn't, you know, actually copy.)
(Show how all copy operations return the same string)
Line 186: Line 186:
'''Interpeter:''' Python 2.3, 2.4, 2.5
'''Interpeter:''' Python 2.3, 2.4, 2.5


Since strings are immutable, this will not copy anything, just point dst to the same string:
Since strings are immutable, all copy operations return the same string. Probably the reference is increased.
src = "Hello"
dst = src


<pre>
There's no way to actually copy a string in Python; all of the standard methods (the unconstrained index [:], copy.copy, copy.deepcopy) all return the same string object, since they're immutable.
>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True
</pre>


==[[Ruby]]==
==[[Ruby]]==