虽然这个问题在实践中没有任何实际用途,但我很好奇Python如何进行字符串实习.我注意到以下内容.
>> "string" is "string"
>> True
Run Code Online (Sandbox Code Playgroud)
这是我所期待的.
你也可以这样做.
>> "strin"+"g" is "string"
>> True
Run Code Online (Sandbox Code Playgroud)
这非常聪明!
但你不能这样做.
>> s1 = "strin"
>> s2 = "string"
>> s1+"g" is s2
>> False
Run Code Online (Sandbox Code Playgroud)
为什么Python不会评估s1+"g",意识到它是相同的s1并指向同一个地址?在最后一个块中实际发生了什么让它返回False?
我开始学习Python(python 3.3),我正在尝试is运算符.我试过这个:
>>> b = 'is it the space?'
>>> a = 'is it the space?'
>>> a is b
False
>>> c = 'isitthespace'
>>> d = 'isitthespace'
>>> c is d
True
>>> e = 'isitthespace?'
>>> f = 'isitthespace?'
>>> e is f
False
Run Code Online (Sandbox Code Playgroud)
似乎空间和问号使is行为表现不同.这是怎么回事?
编辑:我知道我应该使用==,我只是想知道为什么is会这样.