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

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

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

在 Python 中比较字符串最好是使用简单逻辑操作符。
例如,确定一个字符串是否和另外一个字符串匹配。正确的,你可以使用 is equal 或 == 操作符。你也可以使用例如 >= 或 < 来确定几个字符串的排列顺序。

从官方文档上看


1

2

3

4

5

6

7

8

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


1

2

3

4

5

6

7

8

9

10

11

12

>>> 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 地址 字符串是否相同。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#!/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‘

来个简单点的例子:


1

2

3

4

5

6

7

8

9

#-*-conding:utf-8-*-

i=‘xinwen‘;

m=input();

if i==m:

    print(‘yes‘);

else:

    print(‘no‘);

input();

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#!/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() 函数被移除了,所以我以后还是避免少用这个函数。


1

2

3

4

5

6

7

8

9

10

11

12

>>> x=‘a‘

>>> x+‘b‘ is ‘ab‘

False

>>> x+‘b‘ == ‘ab‘

True

>>> cmp(x+‘b‘,‘ab‘)

0

>>> id(x+‘b‘)

32468384L

>>> id(‘ab‘)

46933696L

>>>

注意:


1

2

3

4

5

6

7

>>> a=‘abc‘

>>> b=‘abc‘

>>> a is b

True

>>> id(a) == id(b)

True

>>>

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

原文地址:https://www.cnblogs.com/graybird/p/11487975.html

时间: 2024-08-04 23:37:04

python中的is、==和cmp()比较字符串的相关文章

Python中的列表,元组,字符串之间的相互转化

Python中的列表元组和字符串之间的相互转化需要利用,tuple(),list(),str(). 示例如下: >>> the_string = "hello I'am xiaoli!" >>> #字符串转化为元组 >>> the_tuple = tuple(the_string) >>> the_tuple ('h', 'e', 'l', 'l', 'o', ' ', 'I', "'", 'a

Python中关于list、tuple、字符串的比较

List定义及常用的方法见上一篇博客. Tuple 元组tuple的定义: tuple是一个有序的元素组成的不可变对象的集合,使用小括号()表示,是可迭代对象 元组中数据的访问 支持索引(下标访问) 正负所有索引不可以超界,否则引起IndexError报错 元组通过索引访问 tuple[index] ,index就是索引,使用中括号访问 index(value,[value,[start,stop]]) index是使用值查找,从指定区间指定区间查找元组内的元素是否匹配,匹配到第一个就立即返回索

python中时间戳,datetime 和时间字符串之间得转换

# datetime时间转为字符串def Changestr(datetime1):    str1 = datetime1.strftime('%Y-%m-%d %H:%M:%S')    return str1 # 字符串时间转为时间戳def Changetime(str1):    Unixtime = time.mktime(time.strptime(str1, '%Y-%m-%d %H:%M:%S'))    return Unixtime # datetime时间转为时间戳def

Python学习笔记整理(四)Python中的字符串..

字符串是一个有序的字符集合,用于存储和表现基于文本的信息. 常见的字符串常量和表达式 T1=‘’ 空字符串 T2="diege's" 双引号 T3="""...""" 三重引号块 T4=r'\temp\diege' Raw字符串 抑制(取消)转义,完全打印\tmp\diege,而没有制表符 T5=u’diege' Unicode字符串 T1+T2     合并 T1*3    重复 T2[i]    索引 T2[i:j] 分片

Python中的字符串及用法

字符串是 Python 中最常用的数据类型1.#字符串的定义a = 'westos'b = "what's"c = """用户管理管理系统1.添加用户2.删除用户3.显示用户..... """print(a)print(b)print(c) 2.字符串的特性 字符串是字符的有序集合,可以通过其位置来获得具体的元素.在 python 中,字符串中的字符是通过索引来提取的,索引从 0 开始.python 可以取负值,表示从末尾提取

Python中的数据类型

Python中的数据类型 目录1.字符串2.布尔类型3.整数4.浮点数5.数字6.列表7.元组8.字典9.日期 1.字符串(http://www.cnblogs.com/yjd_hycf_space/p/6846284.html)1.1.如何在Python中使用字符串a.使用单引号(')用单引号括起来表示字符串,例如:str='this is string';print str; b.使用双引号(")双引号中的字符串与单引号中的字符串用法完全相同,例如:str="this is str

python中各种基础类型的转换,二进制,八进制,十进制,十六进制

python中所有类型都是作为对象的形式来存在的. 在python中没有char型,只有字符串类型,这样我们可能将char型转换为整型时极不方便,但是python已经提供了这些转换的内置函数. python 中除了整型,其他进制的只能用字符串来表示 1 int() 可以将 二进制,八进制,十六进制转换成十进制整型 >>> int('1111', 2) 15 >>> int('f', 16) 15 >>> int('17', 8) 15 2 chr()

[Python学习]——序列(1)——初识Python中的序列

我们讲的python中的序列包括:1. 字符串(多个字符组成的一个序列)2. 列表3. 元组 #列表和元组的异同? list=[1,2,3] print type(list) tuple=(1,2,3) print type(tuple) #<相同点> 列表和元组都是容器,可以包含任意类型的元素(甚至是包含一个序列) 列表和元素也都包含元素的顺序 #<差别> 列表是可变的,元组是不可变的 所以通常,在你有一些不确定长度的相同类型队列时使用列表 在已知元素数量的情况下用元组 #<

python中raw_input() 与 input()

参考网址:http://www.cnblogs.com/way_testlife/archive/2011/03/29/1999283.html 在python中如何接收一个输入的字符串. 举个例子: #coding=utf-8 #测试input 和 raw_input x = input("please input :") print x 运行:python 23.py 输入一个数字 please input :9 9 输入一个字符串 please input :aaa Traceb

Python中的函数详解

声明:转载自伯乐在线 Python中的函数,无论是命名函数,还是匿名函数,都是语句和表达式的集合.在Python中,函数是第一个类对象,这意味着函数的用法并没有限制.Python函数的使用方式就像Python中其他值一样,例如字符串和数字等.Python函数拥有一些属性,通过使用Python内置函数dir就能查看这些属性,如下代码所示: def square(x): return x**2 >>> square <function square at 0x031AA230>