1

is在 Python中检查空字符串是否正确?它进行身份检查,同时==测试相等性。

考虑以下内容(使用的想法是从这个答案join中借用的):

>>> ne1 = "aaa"
>>> ne2 = "".join('a' for _ in range(3))
>>> ne1 == ne2
True
>>> ne1 is ne2
False
>>>

所以这里is可以按预期工作。现在看看这段代码:

>>> e1 = ""
>>> e2 = "aaa".replace("a", "")
>>> e3 = "" * 2
>>> e4 = "bbb".join(range(0))
>>> e1, e2, e3, e4
('', '', '', '')
>>> e1 is e2
True
>>> e1 is e3
True
>>> e1 is e4
True
>>> id(e1), id(e2), id(e3), id(e4)
(35963168, 35963168, 35963168, 35963168) # why?
4

4 回答 4

15

检查空字符串的正确方法是:

if yourstring:
   print "string is not empty"

例如bool(yourstring)False如果您的字符串为空。您的示例有效的原因是因为 CPython 缓存了某些字符串和整数并重用它们以提高效率。这是一个实现细节,不应依赖。

于 2012-09-04T12:30:55.830 回答
8

Python 实现可能会选择实习小字符串(好吧,它可能会选择实习任何不可变的东西,真的);Cpython 就是这样做的。

你永远不应该依赖这种行为。如果要检查字符串是否为空字符串,请始终使用mystring == "".

如果您确定要检查的对象始终是一个字符串,您也可以在布尔上下文中评估它(例如,if mystring:),但请记住,这不会将空字符串与0False或区分开来None

于 2012-09-04T12:32:55.280 回答
1

检查空序列(字符串、列表...)的最佳方法是:

if variable:
  pass

来自真值测试

以下值被认为是错误的:

任何空序列,例如,''、()、[]

另请阅读有关比较的文档:

  • is比较身份
  • ==根据类型比较相等性

Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior

于 2012-09-04T12:38:34.447 回答
0

The "is" operator returns true if you are pointing to the same object, as python try to not repeat the strings (it checks if this strings already exists in memory) it will return the same object.

I wouldn't use "is" to compare strings, it's like the "==" operator in Java, it usualy works, but maybe you can get new instances and it will return false, I prefer using == that it will call the method eq and returns True if both strings are equals, even if they are different objects.

于 2012-09-04T12:39:50.340 回答