当前位置:懂科普 >

IT科技

> python判断字符串相等

python判断字符串相等

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

python判断字符串相等怎么操作?一起来看看小编今天的分享吧。

在python中,判断两个变量是否相等或一样,可以使用==或者is来判断,使用“if

例如:

>>>a='f' >>>b='f' >>>a==b True>>> a is b True

值得注意的是,两个字符串来自不同的内存块,内存地址不一样,所以存在==判断是 True,is判断却是 False的情况。

python判断字符串相等

另外,判断不一样可以使用 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

标签: Python 字符串
  • 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/itkeji/zr75g8.html