Beginner: How to copy a string?

Jongwoo Han jwhan at dreamwiz.com
Thu Mar 27 19:48:16 EST 2003


That's because python assigns pointer dynamically. However you don't have to
strictly keep the pointer. Modifying the value of t does not affect content
of s. t points the destination of s as long as it's value is same as s.

>>> s='abc'
>>> id(s)
9761824
>>> t=s[:]
>>> id(t)
9761824
>>> t=s+s
>>> id(t)
9958680
>>> t
'abcabc'
>>> s
'abc'
>>>


<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'.   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.  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.
>
> 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.
>
> -- David






More information about the Python-list mailing list