这里发生了什么?:
>>> a, b, c = ("TEST", "test", "TEST".lower())
>>> map(id, [a,b,c])
[140341845003072, 140341845003216, 140341845003264]
>>> map(str, [a,b,c])
['TEST', 'test', 'test']
>>> map(type, [a,b,c])
[<type 'str'>, <type 'str'>, <type 'str'>]
不应该“TEST”和“TEST”.lower()或“test”和“test”.lower()共享相同的内存位置?
编辑:我知道有一个新副本,但我认为当两个字符串相同时,它们共享相同的内存空间,即:
>>> a = "test"
>>> b = "test"
>>> map(id, (a,b))
[140341845003216, 140341845003216]
>>> a is b
True
在Python 2.7.3上,我得到:
>>> a = "test"
>>> a is a.lower()
False
答案 0 :(得分:1)
docs很清楚。对于string.lower()
:
Return a copy of s, but with upper case letters converted to lower case.
答案 1 :(得分:0)
如果您希望相同的字符串是相同的对象,intern
它们。
默认None, True, False
就是这样;以及源代码中的常量,包括字符串,甚至跨模块。
答案 2 :(得分:0)
不能保证始终如此(相等的字符串始终是同一个对象)。但正如其他人所指出的,它取决于Python的实现(例如,对于使用CPython 3.2.3的Dietrich,它是同一个对象)。
CPython 2.7的代码非常简单:https://github.com/albertz/CPython/blob/master/Objects/stringobject.c#L1984