Copy a string: Difference between revisions

Content deleted Content added
No edit summary
→‎{{header|Python}}: Simplified to be similar to other responses
Line 546:
 
=={{header|Python}}==
<lang python>>>> a = 'hello'
{{works with|Python|2.3, 2.4, and 2.5}}
>>> a = src
Since strings are immutable, all copy operations return the same string. Probably the reference is increased.
>>> b = src[:]
 
True</lang>
<lang python>>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True</lang>
 
To actually copy a string:
 
<lang python>>>> a = 'hello'
>>> b = ''.join(a)
>>> a == b
True
>>> b is a ### Might be True ... depends on "interning" implementation details!
False</lang>
 
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|R}}==