Beginner: How to copy a string?
Terry Reedy
tjreedy at udel.edu
Thu Mar 27 19:49:29 EST 2003
<dbrown2 at yahoo.com> wrote in message
news:d524bdb3.0303271627.739fa868 at posting.google.com...
> I hate to ask this because the answer must be really obvious. So
> obvious in fact that I couldn't find it in the tutorial, FAQ search,
> and other docs, google searches, etc.
>
> I just want to make a copy of a string, say s='abc'.
Why? Given that strings are immutable, there is no point to doing so
(that I can think of ;-). Think about it.
> I understand
> that python is not like some other languages and '=' just assigns a
> name to an existing object and does not copy the object. But there
is
> no s.copy() method apparently.
Again, what would be the point? What would it enable that you cannot
do now?
> The other intuitive way (to me) was to
> try str(s) which I think is similar to the way to copy some other
> types such as list(). That did not work. I did see a newsgroup post
> that said to use [:] and I tried it but this is what I get:
>
> s = 'abc'
> >>> id(s)
> 13356752
> >>> t = s[:]
> >>> id(t)
> 13356752
> >>> t
> 'abc'
>
> Just like with str() it looks like it's still the same object.
Congratulations on actually trying some things out. Here's some more!
>>> import copy
>>> a='abc'
>>> id(a)
7957152
>>> id(copy.copy(a))
7957152
>>> id(copy.deepcopy(a))
7957152
Gee, Python is *really* resistant to copying strings. Same for
numbers.
>>> i=1234567
>>> id(i)
7691536
>>> id(copy.copy(i))
7691536
> Ok, so what's the trick. Please be kind. It's really not obvious
to
> me. In fairness I did see in the FAQ you could convert it to a list
> and rejoin it which I assume would work, but I suspect there is a
more
> direct way.
Why should there be? Anything you do to a string to 'change' its
value generates a new string. It does not matter whether you start
with 'a' or an identical copy. Python goes to some trouble to *not*
make redundant copies of strings (ditto for commonly used 'small'
numbers).
Terry J. Reedy
PS. If you write a C extension, you can poke into the string object
and copy the string buffer, or even change it in place, but then you
are programming in C and not Python, and evading the Python/C API.
More information about the Python-list
mailing list