python中如何使用is、==和cmp()

发布时间:2021-08-09 09:24:33 作者:小新
来源:亿速云 阅读:133

这篇文章主要介绍了python中如何使用is、==和cmp(),具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

在 Python 中比较字符串最好是使用简单逻辑操作符。

例如,确定一个字符串是否和另外一个字符串匹配。正确的,你可以使用 is equal 或 == 操作符。你也可以使用例如 >= 或 < 来确定几个字符串的排列顺序。

从官方文档上看

The operators ``is`` and ``is not`` test for object identity: ``x is
y`` is true if and only if *x* and *y* are the same object. ``x is
not y`` yields the inverse truth value.
 
cmp(...)
 cmp(x, y) -> integer
 
 Return negative if x<y, zero if x==y, positive if x>y.

也就是说 is 用来判断是否是同一个对象,is 是种很特殊的语法,你在其它的语言应该不会见到这样的用法。

python is 主要是判断 2 个变量是否引用的是同一个对象,如果是的话,则返回 true,否则返回 false。
判断数字相等不要用 is 操作符

>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828

为什么两次 is 返回的是不同结果?不是应该都是 true 吗?

因为 string pooling (或叫intern)。 is 相等代表两个对象的 id 相同(从底层来看的话,可以看作引用同一块内存区域)。 至于为什么 “ABC” 被 intern 了而 “a bc” 没有,这是 Python 解析器实现决定的,可能会变。

== 用来判断两个对象的值是否相等(跟 Java 不同,Java 中 == 用来判断是否是同一个对象)。

今天我用 == 来判断两个 IP 地址 字符串是否相同。

#!/usr/bin/python
 
strtmp = '192.169.1.161'
file_object = open(r'public_ip.txt')
try:
 all_the_text = file_object.readlines()
 firstline = all_the_text[0].rstrip()
finally:
 file_object.close()
 
#print firstline
 
#if strtmp == firstline:
s = (strtmp is firstline)
print s
if (strtmp is firstline):
 print 'yes'
else:
 print 'no'

来个简单点的例子:

#-*-conding:utf-8-*-
i='xinwen';
m=input();
if i==m:
 print('yes');
else:
 print('no');
 
input();

在 if 判断语句中非常有用呐!

#!/usr/bin/python
# Filename: if.py
 
number = 23
guess = int(raw_input('Enter an integer : '))
 
if guess == number:
 print 'Congratulations, you guessed it.' # New block starts here
 print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
 print 'No, it is a little higher than that' # Another block
 # You can do whatever you want in a block ...
else:
 print 'No, it is a little lower than that'
 # you must have guess > number to reach here
 
print 'Done'
# This last statement is always executed, after the if statement is executed

cmp() 函数则是相当于 <,==,> 但是在 Python3 中,cmp() 函数被移除了,所以我以后还是避免少用这个函数。

>>> x='a'
>>> x+'b' is 'ab'
False
>>> x+'b' == 'ab'
True
>>> cmp(x+'b','ab')
0
>>> id(x+'b')
32468384L
>>> id('ab')
46933696L
>>>

注意:

>>> a='abc'
>>> b='abc'
>>> a is b
True
>>> id(a) == id(b)
True
>>>

可以看出内容相同的字符串实际上是同一个对象(Java 中直接赋值的字符串也可用 == 来判断,但是使用 new 实例化的对象则需要使用equals(String s) 来判断)。

感谢你能够认真阅读完这篇文章,希望小编分享的“python中如何使用is、==和cmp()”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. windows下安装feedparser
  2. Cocos2d-X 3.1.1创建工程的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:python中遗传算法的示例分析

下一篇:Python中如何使用pyinotify日志监控系统处理日志

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》