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 操作符

>>> 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()的方法了

您可能感兴趣的文章:

  • Python 字符串操作方法大全
  • Python字符串的encode与decode研究心得乱码问题解决方法
  • python 字符串split的用法分享
  • Python中用format函数格式化字符串的用法
  • python判断字符串是否包含子字符串的方法
  • python字符串连接的N种方式总结
  • Python时间戳与时间字符串互相转换实例代码
  • Python去掉字符串中空格的方法
  • python实现字符串和日期相互转换的方法
  • python判断字符串是否纯数字的方法
  • python分割和拼接字符串
  • Python内置的字符串处理函数整理
  • python list 合并连接字符串的方法
  • Python使用MD5加密字符串示例
  • python字符串替换的2种方法
  • Python字符串拼接、截取及替换方法总结分析
  • python统计字符串中指定字符出现次数的方法
  • python使用chardet判断字符串编码的方法
(0)

相关推荐

  • Python中用format函数格式化字符串的用法

    自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足.那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱. 语法 它通过{}和:来代替%. "映射"示例 通过位置 In [1]: '{0},{1}'.format('kzc',18) Out[1]: 'kzc,18' In [2]: '{},{}'.format('kzc',18) Out[2]: 'kzc,18' In [3]: '{1},{0},{1}'.fo

  • python统计字符串中指定字符出现次数的方法

    本文实例讲述了python统计字符串中指定字符出现次数的方法.分享给大家供大家参考.具体如下: python统计字符串中指定字符出现的次数,例如想统计字符串中空格的数量 s = "Count, the number of spaces." print s.count(" ") x = "I like to program in Python" print x.count("i") PS:本站还提供了一个关于字符统计的工具,感兴

  • python实现字符串和日期相互转换的方法

    本文实例讲述了python实现字符串和日期相互转换的方法.分享给大家供大家参考.具体分析如下: 这里用的分别是time和datetime函数 ''' @author: jiangqh ''' import time,datetime # date to str print time.strftime("%Y-%m-%d %X", time.localtime()) #str to date t = time.strptime("2009 - 08 - 08", &q

  • Python字符串拼接、截取及替换方法总结分析

    本文实例讲述了Python字符串拼接.截取及替换方法.分享给大家供大家参考,具体如下: python字符串连接 python字符串连接有几种方法,我开始用的第一个方法效率是最低的,后来看了书以后就用了后面的2种效率高的方法,跟大家分享一下. 先介绍下效率比较低的方法: a = ['a','b','c','d'] content = '' for i in a: content = content + i print content content的结果是:'abcd' 后来我看了书以后,发现书上

  • Python使用MD5加密字符串示例

    Python加密模块有好几个,但无论是哪种加密方式都需要先导入相应的加密模块然后再使用模块对字符串加密. 先导入md5加密所需模块: 复制代码 代码如下: import hashlib 创建md5对象 复制代码 代码如下: m = hashlib.md5() 生成加密串,其中 password 是要加密的字符串 复制代码 代码如下: m.update('password') 获取加密串 复制代码 代码如下: psw = m.hexdigest() 输出 复制代码 代码如下: print psw

  • Python去掉字符串中空格的方法

    我们经常在处理字符串时遇到有很多空格的问题,一个一个的去手动删除不是我们程序员应该做的事情,今天这篇技巧的文章我们就来给大家讲一下,如何用Python去除字符串中的空格.我们先创建一个左右都有N个空格的字符串变量s,看代码: 复制代码 代码如下: >>> s = "   我们    ">>> 去除字符串空格,在Python里面有它的内置方法,不需要我们自己去造轮子了.lstrip:删除左边的空格这个字符串方法,会删除字符串s开始位置前的空格. 复制代

  • python 字符串split的用法分享

    比如我们的存储的格式的: 格式的: 姓名,年龄|另外一个用户姓名,年龄 name:haha,age:20|name:python,age:30|name:fef,age:55 那我们可以通过字符串对象的split方法切割字符串对象为列表. a = 'name:haha,age:20|name:python,age:30|name:fef,age:55' print a.split('|') 返回结果:['name:haha,age:20', 'name:python,age:30', 'name

  • Python时间戳与时间字符串互相转换实例代码

    复制代码 代码如下: #设a为字符串import timea = "2011-09-28 10:00:00" #中间过程,一般都需要将字符串转化为时间数组time.strptime(a,'%Y-%m-%d %H:%M:%S')>>time.struct_time(tm_year=2011, tm_mon=9, tm_mday=27, tm_hour=10, tm_min=50, tm_sec=0, tm_wday=1, tm_yday=270, tm_isdst=-1) #

  • Python字符串的encode与decode研究心得乱码问题解决方法

    为什么会报错"UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)"?本文就来研究一下这个问题. 字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码. decode的作用

  • python使用chardet判断字符串编码的方法

    本文实例讲述了python使用chardet判断字符串编码的方法.分享给大家供大家参考.具体分析如下: 最近利用python抓取一些网上的数据,遇到了编码的问题.非常头痛,总结一下用到的解决方案. linux中vim下查看文件编码的命令 set fileencoding python中一个强力的编码检测包 chardet ,使用方法非常简单.linux下利用pip install chardet实现简单安装 import chardet f = open('file','r') fencodin

  • python字符串连接的N种方式总结

    python中有很多字符串连接方式,今天在写代码,顺便总结一下: 最原始的字符串连接方式:str1 + str2 python 新字符串连接语法:str1, str2 奇怪的字符串方式:str1 str2 % 连接字符串:'name:%s; sex: ' % ('tom', 'male') 字符串列表连接:str.join(some_list) 第一种,想必只要是有编程经验的人,估计都知道,直接用 "+" 来连接两个字符串: 'Jim' + 'Green' = 'JimGreen' 第

  • Python 字符串操作方法大全

    1.去空格及特殊符号 复制代码 代码如下: s.strip().lstrip().rstrip(',') 2.复制字符串 复制代码 代码如下: #strcpy(sStr1,sStr2)sStr1 = 'strcpy'sStr2 = sStr1sStr1 = 'strcpy2'print sStr2 3.连接字符串 复制代码 代码如下: #strcat(sStr1,sStr2)sStr1 = 'strcat'sStr2 = 'append'sStr1 += sStr2print sStr1 4.查

  • python判断字符串是否纯数字的方法

    本文实例讲述了python判断字符串是否纯数字的方法.分享给大家供大家参考.具体如下: 判断的代码如下,通过异常判断不能区分前面带正负号的区别,正则表达式可以根据自己需要比较灵活的写,通过isdigit方法用来判断是否是纯数字,测试代码如下 复制代码 代码如下: #!/usr/bin/python # -*- coding: utf-8 -*- a = "1" b = "1.2" c = "a" #通过抛出异常 def is_num_by_exc

  • python分割和拼接字符串

    关于string的split 和 join 方法对导入os模块进行os.path.splie()/os.path.join() 貌似是处理机制不一样,但是功能上一样. 1.string.split(str=' ',num=string.count(str)): 以str为分隔,符切片string,如果num有指定值,则仅分隔num个子字符串.S.split([sep [,maxsplit]]) -> 由字符串分割成的列表 返回一组使用分隔符(sep)分割字符串形成的列表.如果指定最大分割数,则在

  • python字符串替换的2种方法

    python 字符串替换 是python 操作字符串的时候经常会碰到的问题,这里简单介绍下字符串替换方法. python 字符串替换可以用2种方法实现: 1是用字符串本身的方法. 2用正则来替换字符串 下面用个例子来实验下: a = 'hello word' 把a字符串里的word替换为python 1.用字符串本身的replace方法 复制代码 代码如下: a.replace('word','python') 输出的结果是hello python 2.用正则表达式来完成替换: 复制代码 代码如

  • python判断字符串是否包含子字符串的方法

    本文实例讲述了python判断字符串是否包含子字符串的方法.分享给大家供大家参考.具体如下: python的string对象没有contains方法,不用使用string.contains的方法判断是否包含子字符串,但是python有更简单的方法来替换contains函数. 方法1:使用 in 方法实现contains的功能: site = 'http://www.jb51.net/' if "jb51" in site: print('site contains jb51') 输出结

  • Python内置的字符串处理函数整理

    str='python String function' 生成字符串变量str='python String function' 字符串长度获取:len(str)例:print '%s length=%d' % (str,len(str)) 字母处理全部大写:str.upper()全部小写:str.lower()大小写互换:str.swapcase()首字母大写,其余小写:str.capitalize()首字母大写:str.title()print '%s lower=%s' % (str,st

  • python list 合并连接字符串的方法

    比如下面一个list 复制代码 代码如下: binfo = ['lao','wang','python'] 我们通过help方法得知,可以用string的join方法来解决. 下面我们通过空格来连接3个单词: 复制代码 代码如下: content = " ".join(binfo)print content 结果是:lao wang python

随机推荐