python 字符串(与 space)匹配

python string (with space) matching

在尝试消除字符串列表中的几个字符串时,我尝试使用类似于以下的简单代码:

>>> s = ['a b', 'c d', 'e f', 'g h']
>>> for i in s:
...     if i is not 'e f':
...         print(i)
...
a b
c d
e f    # this should not get printed, right?
g h

我无法理解潜在的行为? 你能解释一下吗?因为以下似乎合乎逻辑,上面也应该相应地起作用

>>> if 'a b' is not 'a b':
...     True
... else:
...     False
...
False
>>> s = ['a', 'c', 'e', 'g']
>>> for i in s:
...     if i is not 'e':
...         print(i)
...
a
c
g

空格需要特殊处理吗?我错过了什么?

is not 是基于身份的测试;当它对字符串起作用时,这是由于字符串的驻留或小的字符串缓存;这是一个永远不应依赖的实现细节。

一般不要使用 is/is not,除非与 None 进行比较,直到您真正理解它在做什么。你想要 != 在这里,tests value (do the two objects represent the same logical information?), not is not, which tests identity(这两个东西指的是完全相同的对象吗?)。

如果你想强制这个工作,你可以做一些可怕的事情,比如明确地 interning 所有涉及的字符串,但这不会节省任何工作(工作花在实习他们上),它通常不受欢迎。