0%

Python杂记


作者: 耗子007


最近被python的条件坑了一波,在此小计一下。
python的IF的条件判断和C是一致的,0表示False,非0表示True。这本没什么问题,坑爹的是,很多函数的成功返回0,而失败返回-1,这就很容易被坑了。
先看看0和-1的情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

root@rtos:/home/work/rtos# python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> if 0:
... print("0 is True")
... else:
... print("0 is False")
...
0 is False
>>> if -1:
... print("-1 is True")
... else:
... print("-1 is False")
...
-1 is True

字符串的find函数,在查找失败的时候返回-1,成功时返回匹配的起始下标。当匹配的起始下标是0和查找失败的时候,在if判断时候需要注意了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

>>> tmp = "abcdefg"
>>> a = "abc"
>>> b = "bcd"
>>> if tmp.find(a):
... print("%s find in %s" % (a, tmp))
... else:
... print("%s cannot find in %s" % (a, tmp))
...
abc cannot find in abcdefg

>>> if tmp.find(b):
... print("%s find in %s" % (b, tmp))
... else:
... print("%s cannot find in %s" % (b, tmp))
...
bcd find in abcdefg

>>> c = "234"
>>> if tmp.find(c):
... print("%s find in %s" % (c, tmp))
... else:
... print("%s cannot find in %s" % (c, tmp))
...
234 find in abcdefg