Copy a string: Difference between revisions

Line 339:
Since strings are immutable, all copy operations return the same string. Probably the reference is increased.
 
<prepython>
>>> src = "hello"
>>> a = src
Line 348:
>>> src is a is b is c is d
True
</prepython>
 
To actually copy a string:
 
<prepython>
>>> a = 'hello'
>>> b = ''.join(a)
>>> a == b
True
>>> b is a ### Might be True ... depends on "interning" implementation details!
>>> b is a
False
</prepython>
 
As a result of object "interning" some strings such as the empty string and single character strings like 'a' may be references to the same object regardless of copying. This can potentially happen with any Python immutable object and should be of no consequence to any proper code.
 
Be careful with ''is'' - use it only when you want to compare the identity of the object. To compare string values, use the ''=='' operator. For numbers and strings any given Python interpreter's implementation of "interning" may cause the object identities to coincide. Thus any number of names to identical numbers or strings might become references to the same objects regardless of how those objects were derived (even if the contents were properly "copied" around). The fact that these are immutable objects makes this a reasonable behavior.
 
=={{header|Raven}}==
Anonymous user