Beginner: How to copy a string?
Delaney, Timothy C (Timothy)
tdelaney at avaya.com
Thu Mar 27 19:59:09 EST 2003
> From: dbrown2 at yahoo.com [mailto:dbrown2 at yahoo.com]
>
> I just want to make a copy of a string, say s='abc'. I understand
>
> 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.
Before anything else ...
Why do you want to copy a string? What use do you *actually* have for a copy of a string?
Now, onto the answer.
1. In general, you don't. Strings are immutable, so a copy of a string is indistinguishable from the original except by its ID.
2. It is impossible to guarantee that you will get a copy of a string. An implementation is free to do whatever it likes with strings e.g. it could decide that *every* string with the same value will refer to the same object - or it could have every string be a separate object.
3. CPython interns all literal strings that look like python identifiers. 'abc' (without the quotes) would be a valid python identifier so it is interned. This is done partially so that identifier lookups in dictionaries are as fast as possible.
4. A string copy using copy() or [:] is special-cased by the string object to simply return `self`.
5. Given all that, to do what you want, the following will work with current versions of Python (no guarantees of future versions though):
s = 'abc'
print id(s)
t = s[:]
print id(t)
u = t[:1] + t[1:]
print id(u)
print repr(s)
print repr(t)
print repr(u)
Note however what happens if you try to copy an empty string ...
s = ''
print id(s)
t = s[:]
print id(t)
u = t[:1] + t[1:]
print id(u)
print repr(s)
print repr(t)
print repr(u)
So, I come back to my original question - why do you want to copy a string?
Tim Delaney
More information about the Python-list
mailing list