python 如何比較字符串是否一樣

在python中,判斷兩個變量是否相等或一樣,可以使用==或者is來判斷;判斷不一樣可以使用 is not。

示例

在這裡插入圖片描述

使用註意事項

1.有時候兩個字符串打印出來看著一樣,但是判斷卻是False?

如果兩個字符串末尾有其他符號,比如回車‘\n’,print的時候無法發現的,所以需要strip:

a=a.strip()
b=b.strip()
if a==b:
	print "True"

2.有時候==判斷是 True ,is 判斷卻是 False?

這是因為兩個字符串來自不同的內存塊,內存地址不一樣

id() 函數用於獲取對象的內存地址。

(ob1 is ob2) 等價於 (id(ob1) == id(ob2)) id函數可以獲得對象的內存地址,如果兩個對象的內存地址是一樣的,那麼這兩個對象肯定是一個對象。和is是等價的.

在這裡插入圖片描述

3.還有一種情況是兩個對象用is判斷是False,用id判斷卻是True。

原理比較復雜,如下:

In [1]: def bar(self, x):
...:     return self.x + y
...: 
In [2]: class Foo(object):
...:     x = 9
...:     def __init__(self ,x):
...:         self.x = x
...:     bar = bar
...:     
In [3]: foo = Foo(5)
In [4]: foo.bar is Foo.bar
Out[4]: False
In [5]: id(foo.bar) == id(Foo.bar)
Out[5]: True

真實情況是當執行.操作符的時候,實際是生成瞭一個proxy對象,foo.bar is Foo.bar的時候,兩個對象順序生成,放在棧裡相比較,由於地址不同肯定是False,但是id(foo.bar) ==id(Foo.bar)的時候就不同瞭,首先生成foo.bar,然後計算foo.bar的地址,計算完之後foo.bar的地址之後,就沒有任何對象指向foo.bar瞭,所以foo.bar對象就會被釋放。然後生成Foo.bar對象,由於foo.bar和Foo.bar所占用的內存大小是一樣的,所以又恰好重用瞭原先foo.bar的內存地址,所以id(foo.bar) == id(Foo.bar)的結果是True。

下面內容由郵件Leo Jay大牛提供,他解釋的更加通透。

用id(expression a) == id(expression b)來判斷兩個表達式的結果是不是同一個對象的想法是有問題的。

foo.bar 這種形式叫 attribute reference [1],它是表達式的一種。foo是一個instance object,bar是一個方法,這個時候表達式foo.bar返回的結果叫method object [2]。

根據文檔:

When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object.

foo.bar本身並不是簡單的名字,而是表達式的計算結果,是一個 method object,在id(foo.bar)這樣的表達式裡,method object隻是一個臨時的中間變量而已,對臨時的中間變量做id是沒有意義的。

一個更明顯的例子是,

print id(foo.bar) == id(foo.__init__)  輸出的結果也是True

看 id 的文檔[3]:

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. CPython implementation detail: This is the address of the object in memory.

隻有你能保證對象不會被銷毀的前提下,你才能用 id 來比較兩個對象。所以,如果你非要比的話,得這樣寫:

fb = foo.bar 
Fb = Foo.bar 
print id(fb) == id(Fb)

即把兩個表達式的結果綁定到名字上,再來比是不是同一個對象,你才能得到正確的結果。

is表達式 [4] 也是一樣的,你現在得到瞭正確的結果,完全是因為 CPython 現在的實現細節決定的。

現在的is的實現,是左右兩邊的對象都計算出來,然後再比較這兩個對象的地址是否一樣。

萬一哪天改成瞭,先算左邊,保存地址,把左邊釋放掉,再算右邊,再比較的話,你的is的結果可能就錯瞭。

官方文檔裡也提到瞭這個問題 [5]。

我認為正確的方法也是像id那樣,先把左右兩邊都計算下來,並顯式綁定到各自的名字上,然後再用is判斷。

python字符串判斷相等總結

判斷字符串相等使用==,不使用is和cmp()函數

cmp() 函數則是相當於 <,==,> 但是在 Python3 中,cmp() 函數被移除瞭,所以我以後還是避免少用這個函數。

#-*-conding:utf-8-*-
i='新聞';
m=input();
if i==m:
 print('yes');
else:
 print('no');  
input();
if second_company_name == u'中外運長航' or second_company_name == u'長航集團':
                print(u'忽略中外運長航和長航集團的子公司')
                continue

在 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```
## strip 去掉字符串其他符號
str1 = str1.strip() #去掉字符串中其他符號包括換行符等等
str2 = str2.strip()
if str2 == str1:
    ... #自己的代碼
## == 與 is的區別

python中,使用==來比較兩個**對象的值**是否相等,而java 則使用== 比較兩個**對象**是否是同一對象

譬如,java中比較字符串,一般使用equal 方法,來比較兩個對象的值是否相等,而不使用==

相比較的,python 使用**is** 來比較兩個對象是否是同一對象。

is 用來判斷是否是同一個對象,is 是種很特殊的語法,你在其它的語言應該不會見到這樣的用法。

官方文檔解釋:

```python
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.

註意:內容相同的字符串實際上是同一個對象

>>> a='abc'
>>> b='abc'
>>> a is b
True
>>> id(a) == id(b)
True
>>>
>```
(Java 中直接賦值的字符串也可用 == 來判斷,但是使用 new 實例化的對象則需要使用equals(String s) 來判斷)
## 判斷數字相等不要用 is 操作符
```python
>>> 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 地址 字符串是否相同。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: