How can you copy (clone) a string?

Greg Ewing see at my.signature
Thu Oct 5 21:36:18 EDT 2000


Joal Heagney wrote:
> 
> However, I don't understand it
> all, because when you just create the strings as follows:
> >>> a = 'aa'
> >>> b = 'aa'
> >>> c = 'aa'
> >>> d = 'aa'
> >>> id(a), id(b), id(c), id(d)
> (134879088, 134879088, 134879088, 134879088)

In the interests of speed, the strings used internally
to hold the names of variables, attributes, etc. are
"interned" (i.e. stored uniquely in a table). The compiler
also does this to string constants that you write into
your code, such as 'aa' above, in some cases, both to
save space, and just in case you want to use one
in a getattr call or something like that.

However, this is not done for strings that you compute
at runtime in some way. That would take a lot of time
for hardly any benefit, since it's extremely rare to
use a computed string as a variable name.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list