Python中is和==的區別的

來源:互聯網
上載者:User

標籤:back   false   地址   語言   不同的   val   str   ack   比較   

在python中,is檢查兩個對象是否是同一個對象,而==檢查他們是否相等.

str1 = ‘yangshl‘str2 = ‘yang‘ + ‘shl‘print(‘str1 == str2:‘, str1 == str2)print(‘str1 is str2:‘, str1 is str2)print("id(str1):", id(str1))print("id(str2):", id(str2))

 輸出結果是:

str1 == str2: True
str1 is str2: True
id(str1): 17102416
id(str2): 17102416

問題:str1 是 一個對象嗎??從id上看,的確是一個。

 

one = ‘yang‘two = ‘shl‘str3 = one+twoprint(‘str1 == str3:‘, str1 == str3)print(‘str1 is str3:‘, str1 is str3)print("id(str1):", id(str1))print("id(str3):", id(str3))

的結果是:

str1 == str3: True
str1 is str3: False
id(str1): 17102416
id(str3): 17102528

 

str3的計算結果明明是 yangshl。但是它和yangshl是不同的對象,但是value是相同的。

str4 = str(‘yangshl‘)str5 = str(‘yangshl‘)print(‘str4 == str5:‘, str4 == str5)print(‘str4 is str5:‘, str4 is str5)print("id(str4):", id(str4))print("id(str5):", id(str5))

結果是:
str4 == str5: True
str4 is str5: True
id(str4): 17102416
id(str5): 17102416

java中會認為是不同的對象。但是在python中這說明使用 str和字串直接量是一個對象。

 

如果比對list呢?

list1 = [1]list2 = [1]print(‘list1 == list2:‘, list1 == list2)print(‘list1 is list2:‘, list1 is list2)print("id(list1):", id(list1))print("id(list2):", id(list2))

結果是:
list1 == list2: True
list1 is list2: False
id(list1): 16919944
id(list2): 16920520

 

所以如果你要比較兩個值是否相同就用==,如果比較是否是同一個對象就用is。

其實python中的is比較的對象很像C語言中的指標,只有地址相同的指標才是同一個指標。

 

Python中is和==的區別的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.