Python之字串方法find( )
阿新 • • 發佈:2019-01-07
不理解函式的含義會影響對程式碼的理解,舉例如下。
e.g.模擬手機通訊錄中的電話號碼聯想功能之基本思路。
程式碼:search = '188'
num_a = '1386-188-0006'
num_b = '1881-222-0006'
print(search + ' is at ' + str(num_a.find(search)) + ' to ' + str(num_a.find(search) + len(search)) + ' of num_a')
print(search + ' is at ' + str(num_b.find(search)) + ' to ' + str(num_b.find(search) + len(search)) + ' of num_b')
結果:188 is at 5 to 8 of num_a
188 is at 0 to 3 of num_b
Python中的find( )方法
用於檢驗字串是否包含子字串str,如果已指定beg和end範圍,則檢驗將在制定範圍內。
如果包含字串,返回開始的索引值,否則返回-1。
語法:str.find(str,beg=0,end=len(string))
str——指定檢索的字串
beg——開始索引,預設為0
end——結束索引,預設為字串的長度
num_a.find(search) 指在變數num_a中查詢search值所對應的索引號;未有給出beg和end值即指預設。
而在num_a.find(search)外巢狀str( )則是避免print函式中的數值型資料和字元型資料合併時報錯。