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

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

常常寫 shell 腳本知道,字符串判斷能夠用 =,!= 數字的判斷是 -eq,-ne 等,可是 Python 確不是這樣子地。
因此做爲慢慢要轉換到用 Python 寫腳本,這些基本的東西必需要掌握到骨子裏!shell

在 Python 中比較字符串最好是使用簡單邏輯操做符。
例如,肯定一個字符串是否和另一個字符串匹配。正確的,你可使用 is equal 或 == 操做符。你也可使用例如 >= 或 < 來肯定幾個字符串的排列順序。ide

從官方文檔上看函數

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%98post

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 解析器實現決定的,可能會變。spa

== 用來判斷兩個對象的值是否相等(跟 Java 不一樣,Java 中 == 用來判斷是不是同一個對象)。
今天我用 == 來判斷兩個 IP 地址 字符串是否相同。code

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 判斷語句中很是有用吶!blog

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() 函數被移除了,因此我之後仍是避免少用這個函數。ip

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) 來判斷)。

相關文章
相關標籤/搜索