python判斷字元串相等怎麼操作?一起來看看小編今天的分享吧。
在python中,判斷兩個變量是否相等或一樣,可以使用==或者is來判斷,使用“if
例如:
>>>a='f' >>>b='f' >>>a==b True>>> a is b True
值得注意的是,兩個字元串來自不同的內存塊,內存地址不一樣,所以存在==判斷是 True,is判斷卻是 False的情況。
另外,判斷不一樣可以使用 is not,使用“if
例如:
>>> a is not b False>>> a != b False
有時候兩個字元串打印出來看着一樣,但是判斷卻是False,如果兩個字元串末尾有其他符號,比如回車鍵的時候無法發現的,所以需要strip:
a=a.strip() b=b.strip() if a==b:print "True"
還有一種情況是兩個對象用is判斷是False,用id判斷卻是True。原理比較複雜,如下:
In [1]: def bar(self, x):
...: return self.x + y
...:
In [2]: class Foo(object):
...: x = 9
...: def __init__(self ,x):
...: self.x = x
...: bar = bar
...:
In [3]: foo = Foo(5)
In [4]: foo.bar is Foo.bar
Out[4]: False
In [5]: id(foo.bar) == id(Foo.bar)
Out[5]: True