How can you copy (clone) a string?

Paul Robinson paul.robinson at businesscollaborator.com
Tue Oct 3 10:26:29 EDT 2000


Peter.Rupp at ual.com wrote:
> 
> All,
> I have a bonafide need to create copies of strings in a python program
> (as opposed to a reference to the original).

<snip>

> Let me illustrate......
> 
> from copy import *
> a='a'
> id(a)
> 1073972424
> b=deepcopy(a)
> id(b)
> 1073972424

I'm sure someone will correct me if I'm wrong but I don't think this is
possible - given the way that Python stores small strings like these the
ids will always be the same.

Max Møller Rasmussen wrote:
> > 
> > Just use slice:
> > 
> > a = 'a'
> > b = a[:]

This doesn't change the fact that id(a) == id(b).

Perhaps if you explain what your "bonafide need" is someone would
suggest a reason a) why you don't need to do it or b) how you can do it
in an alternative way.
The immutability of strings means that you are never going to have a
problem changing a string object which is referenced in a number of
places - why do you need "a copy".

        Paul.




More information about the Python-list mailing list