gpt4 book ai didi

python - 使用 `is` 检查空字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:53 25 4
gpt4 key购买 nike

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

考虑以下(使用 join 的想法是从 this answer 借来的):

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

所以这里的正如人们所期望的那样工作。现在看看这段代码:

>>> 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?

最佳答案

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

if yourstring:
print "string is not empty"

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

关于python - 使用 `is` 检查空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com