2011-08-21 165 views
0

我一直认为在条件中使用-1总是与写作False(布尔值)相同。但是从我的代码,我得到不同的结果:在Python中,-1和False有区别吗?

用真和假:

def count(sub, s): 
    count = 0 
    index = 0 
    while True: 
     if string.find(s, sub, index) != False: 
      count += 1 
      index = string.find(s, sub, index) + 1 
     else: 
      return count 


print count('nana', 'banana') 

结果:需要长期的译员回应。


使用1和-1:

def count(sub, s): 
    count = 0 
    index = 0 
    while 1: 
     if string.find(s, sub, index) != -1: 
      count += 1 
      index = string.find(s, sub, index) + 1 
     else: 
      return count 


print count('nana', 'banana') 

结果:1

为什么使用-1和1给我正确的结果,而使用布尔值true和false不要?

+0

[为什么1 == True但是2!= True在Python?](http://stackoverflow.com/questions/7134984/why-does-1-true-but-2-true-in -python) – agf

+0

我们刚刚在Python中提出了一个关于'True'和'False'的问题。 '-1'在Python中不是'False','0'是False。在发布问题之前,请搜索这样的内容。 – agf

+0

另请参阅[python-true-false](http://stackoverflow.com/questions/5119709/python-true-false),[why-cant-python-handle-true-false-values-as-i-expect ](http://stackoverflow.com/questions/2055029/why-cant-python-handle-true-false-values-as-i-expect),[is-false-0-and-true-1-in-蟒-AN-实现细节或 - 是 - 它担保](http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail -or-it-it-guarantee),[true-false-true] – agf

回答

3

string.find没有返回一个布尔所以string.find('banana', 'nana', index)NEVER换货政... 0False),无论index的值如何。

>>> import string 
>>> help(string.find) 
Help on function find in module string: 

find(s, *args) 
    find(s, sub [, start [, end]]) -> int 

    Return the lowest index in s where substring sub is found, 
    such that sub is contained within s[start,end]. Optional 
    arguments start and end are interpreted as in slice notation. 

    Return -1 on failure. 
>>> 

你举的例子只是重复:

index = string.find('banana', 'nana', 0) + 1 # index = 3 
index = string.find('banana', 'nana', 3) + 1 # index = 0 

-1版本的作品,因为它正确解释的string.find返回值!

+0

+1用于引用文档!但请引用你的消息来源。 –

+0

'False == 0'产生'True'。 –

2

假是bool类型,这是一个子int类型的,并且其值为0

在Python,False类似于使用0,而不是-1

1

有之间的差平等和转换为实况测试一个布尔值,历史和灵活性方面的原因:

>>> True == 1 
True 
>>> True == -1 
False 
>>> bool(-1) 
True 
>>> False == 0 
True 
>>> bool(0) 
False 
>>> True == 2 
False 
>>> bool(2) 
True 
0

我一直认为在条件使用-1常是一样的书写假(布尔值)。

1)不,这是永远不变的,我无法想象为什么你会想到这一点,更别说总是这样想了。除非由于某种原因,否则你只使用ifstring.find什么的。

2)您不应该首先使用string模块。直接从文档报价:

说明
警告:最让你看到这里通常不采用时下的代码。 从Python 1.6开始,许多这些函数在标准字符串对象上实现为 方法。他们以前通过一个名为strop的内置模块来实现 ,但strop现在已经过时。

所以不是string.find('foobar', 'foo'),我们使用str类本身(类'foobar''foo'属于)的.find方法;并且由于我们有该类的对象,所以我们可以进行绑定方法调用,因此:'foobar'.find('foo')

3)字符串的.find方法返回一个数字,告诉你在哪里找到子字符串,如果找到了。如果未找到子字符串,则返回-1。在这种情况下它不能返回0,因为这意味着“在开始时被发现”。

4)False将比较等于0。值得注意的是,Python实际上实现了bool类型作为int的子类。

5)无论您使用何种语言,都不应与布尔文字进行比较。很简单,x == False或等价物是不正确的。它在清晰度方面没有任何收获,并创造出错机会。

你永远不会说“如果这是真的,它正在下雨,我将需要一把伞”,尽管这在语法上是正确的。无关紧要;它不比更明显的“如果下雨,我需要一把雨伞”更有礼貌,也不更清晰。

如果要将值用作布尔值,则将其用作布尔值。如果您想要使用比较结果(即“是等于-1还是不是?”),则执行比较。

相关问题