Beginner: How to copy a string?
dbrown2 at yahoo.com
dbrown2 at yahoo.com
Thu Mar 27 19:27:15 EST 2003
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