在Python使用字符串的過(guò)程中,如果遇到很多的字符串,想要查找到想要的字符串有些困難。本文主要介紹Python字符串查找的幾種方法:find方法、index方法、rfind方法、rindex方法。具體請(qǐng)看如下內(nèi)容:
find方法
find方法獲取值時(shí),如果要查找的值不存在,會(huì)返回-1
str.find(str,beg=0,end=len(string))
使用實(shí)例
#stringinwhichwehavetofindthesub_string
str="Helloworld,howareyou?"
#sub_stringtofindthegivenstring
sub_str="how"
#findbysub_str
print(str.find(sub_str))
#findbysub_strwithslice:startindex
print(str.find(sub_str,10))
#findbysub_strwithslice:startindexandslice:endindex
print(str.find(sub_str,10,24))
#findasub_strthatdoesnotexist
sub_str="friend"
#findbysub_str
print(str.find(sub_str))
#findasub_strwithdifferentcase
sub_str="HOW"
#findbysub_str
print(str.find(sub_str))
輸出
13
13
13
-1
-1
index方法
在獲取值得索引時(shí),如果不存在值,會(huì)報(bào)錯(cuò)
str.index(str,beg=0,end=len(string))
使用實(shí)例
defsecond_index(text:str,symbol:str):
"""
returnsthesecondindexofsymbolinagiventext
"""
try:
returntext.index(symbol,text.index(symbol)+1)
exceptValueError:
returnNone
if__name__=='__main__':
#These"asserts"usingonlyforself-checkingandnotnecessaryforauto-testing
print('Example:')
print(second_index("sims","s"))
assertsecond_index("sims","s")==3,"First"
assertsecond_index("findtheriver","e")==12,"Second"
assertsecond_index("hi","")isNone,"Third"
assertsecond_index("himayor","")isNone,"Fourth"
assertsecond_index("himrMayor","")==5,"Fifth"
print('Youareawesome!Alltestsaredone!GoCheckit!')
注意:
find()和index()只能找到第一個(gè)索引值。如果指定字符同時(shí)存在多個(gè),只會(huì)輸出第一個(gè)指定字符的索引值。
rfind和rindex方法用法和上面一樣,只是從字符串的末尾開(kāi)始查找。
以上內(nèi)容為大家介紹了Python中字符串如何查找?希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。