Python Strings

Thomas Wouters thomas at xs4all.net
Sun Aug 20 06:22:59 EDT 2000


On Sun, Aug 20, 2000 at 02:29:39AM -0400, Mike Fletcher wrote:

> target = fromstr[:]

> Of course, the implementation could, I suppose, some day optimise away that
> to become a copy of the pointer instead.  Out of curiosity, why do you want
> this?  Unless you're interfacing with C and are using the string as a
> buffer, you'll not get much benefit from the copying.  The hash values will
> still be equal, and the only way to tell them apart is doing an id( ).

Actually, no. Python 'intern's small strings and strings that are constants
in your program. The two string objects *might* be different objects with
the same value, but the chance they are actually the same object is pretty
high. Try it and see! The 'is' comparison and the id() function can be used
to prove it ;)

>>> s1 = "Spam"
>>> s2 = s1[:]
>>> print id(s1), id(s2)
135391960 135391960

>>> s1 = "Spam"
>>> s2 = "Spam And Eggs"
>>> print id(s1), id(s2[:4]) 
135391960 135400616
>>> print id(s1), id(intern(s2[:4]))
135391960 135391960

>>> print intern.__doc__
intern(string) -> string

`Intern'' the given string.  This enters the string in the (global)
table of interned strings whose purpose is to speed up dictionary lookups.
Return the string itself or the previously interned string object with the
same value.

PS: python-list is not a listserv mailinglist, it's a Mailman mailinglist!

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list