python中index()與find()的區別

來源:互聯網
上載者:User

標籤:python   find函數   index函數   區別   valueerror substring   

起因:在排查錯誤時定位在判斷語句這一行:if testlist.index(‘T‘):報錯:ValueError: substring not found。原來是index()和find()沒區分清楚。find()尋找失敗會返回-1,不會影響程式運行。一般用find!=-1或者find>-1來作為判斷條件。1.index描述

Python index() 方法檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個異常。

文法

index()方法文法:

str.index(str, beg=0, end=len(string))
參數
  • str -- 指定檢索的字串
  • beg -- 開始索引,預設為0。
  • end -- 結束索引,預設為字串的長度。
返回值

如果包含子字串返回開始的索引值,否則拋出異常。

執行個體

以下執行個體展示了index()方法的執行個體:

#!/usr/bin/pythonstr1 = "this is string example....wow!!!";str2 = "exam";print str1.index(str2);print str1.index(str2, 10);print str1.index(str2, 40);
以上執行個體輸出結果如下:

1515Traceback (most recent call last):  File "test.py", line 8, in   print str1.index(str2, 40);ValueError: substring not foundshell returned 1

2.find描述

Python find() 方法檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,如果包含子字串返回開始的索引值,否則返回-1。

文法

find()方法文法:

str.find(str, beg=0, end=len(string))
參數
  • str -- 指定檢索的字串
  • beg -- 開始索引,預設為0。
  • end -- 結束索引,預設為字串的長度。
返回值

如果包含子字串返回開始的索引值,否則返回-1。

著作權聲明:歡迎轉載,轉載請註明出處http://blog.csdn.net/ztf312/

python中index()與find()的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.