【问题标题】:Comparison with unicode string in if-condition (python) [duplicate]与if-condition(python)中的unicode字符串比较[重复]
【发布时间】:2011-09-09 14:24:09
【问题描述】:

可能重复:
Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?

我将跳过我告诉你我如何测试我的代码并直接跳到问题的部分。

Python 似乎在将一个 unicode 字符串拆分为 if 语句中的另一个内联 unicode 字符串时遇到了一些问题。

>>>zone = u'domain.com.'
>>>zone[-1:]
u'.'

>>>u'.' is u'.' #works fine
True
>>> z[-1:] == u'.' #works fine
True
>>> zone[-1:] is u'.' # FAILS !
False

这是我的实际代码sn-p

>>>if zone[-1:] is not u'.':
>>>    #this line will always run !

如果我将“不是”更改为 != 代码工作正常!

有谁知道为什么“是”导致比较失败?

【问题讨论】:

标签: python if-statement unicode-string


【解决方案1】:

这是因为字符串是 Python 中的对象 --- 当你对一个字符串进行切片时,你会创建一个新的。

它比这稍微复杂一些,但这就是它的要点。

解决方案:使用==!= 而不是isis not

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2016-05-31
    • 1970-01-01
    • 2016-07-08
    相关资源
    最近更新 更多