刘荣星的博客

  • 留言
  • About
一个关注Linux/BSD运维等相关知识的博客
  1. 首页
  2. Python
  3. Python 操作符
  4. 正文

python中的is、==和cmp()比较字符串

2014-01-04 228009点热度 0人点赞 0条评论

python 中的is、==和cmp(),比较字符串

经常写 shell 脚本知道,字符串判断可以用 =,!= 数字的判断是 -eq,-ne 等,但是 Python 确不是这样子地。
所以作为慢慢要转换到用 Python 写脚本,这些基本的东西必须要掌握到骨子里!

在 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 操作符
http://onlypython.group.iteye.com/group/wiki/852-%E6%93%8D%E4%BD%9C%E7%AC%A6is%E7%9A%841%E4%B8%AA%E8%AF%A1%E5%BC%82%E9%97%AE%E9%A2%98

>>> 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) 来判断)。

标签: operator python
最后更新:2014-01-04

JavasBoy

这个人很懒,什么都没留下

点赞

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

最新 热点 随机
最新 热点 随机
CentOS7 python2 安装 elasticsearch 模块 在VMWare Workstation虚拟机里使用 yubikey Gentoo Gnome 登陆界面开启触摸板轻击 python3去除emoji表情符号 记录几个内网广播包 Linux Mint 20 gnome-terminal 使用等距更纱黑体 SC字体
今天更换主题为Prower V2 解决了苹果系统下运行AECS4假死现象 charset=utf-8和 charset=gb2312编码的不同 nginx 301跳转到带www域名方法rewrite VB程序设计实训 Ubuntu12.04无法使用vim系统剪贴板解决方法
分类
  • After Effects / 20篇
  • Apple / 5篇
  • Archlinux / 4篇
  • Bash / 2篇
  • Cinema 4D / 1篇
  • Docker / 1篇
  • eMule / 2篇
  • FreeBSD / 9篇
  • Gentoo / 1篇
  • Go / 2篇
  • gpg / 1篇
  • Graphics / 15篇
  • Haproxy / 1篇
  • ingress / 1篇
  • IntelliJ_IDEA / 1篇
  • java / 2篇
  • kafka / 1篇
  • Linux / 24篇
  • MySQL / 3篇
  • network / 3篇
  • Network / 4篇
  • Nginx / 5篇
  • Perl / 4篇
  • Python / 9篇
  • Python 操作符 / 1篇
  • Python 正则 / 2篇
  • rose / 1篇
  • Script / 4篇
  • Tornado / 1篇
  • Vim / 5篇
  • 学习 / 24篇
  • 电脑 / 29篇
  • 那不勒斯 / 1篇
  • 随笔 / 45篇
标签聚合
Linux python After Effects FreeBSD Graphics MAC AE 双系统

COPYRIGHT © 2025 刘荣星的博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang