Python中字符串如何查找?
发布时间:2025-11-24 11:36:07

在Python使用字符串的过程中,如果遇到很多字符串,很难找到想要的字符串。本文主要介绍了Python字符串搜索的几种方法:find方法, index方法、rfind方法,rindex方法。具体请看如下内容:
find方法
当find方法获得值时,如果要找到的值不存在,将返回-1
str.find(str,beg=0,end=len(string))
使用实例
#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方法
在获得值得索引时,如果没有值,就会报错
str.index(str,beg=0,end=len(string))
使用实例
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!Alltestsaredone!GoCheckit!')注意:find()和index()只能找到第一个索引值。若指定字符同时存在多个,则只能输出第一指定字符的索引值。
rfind和rindex的方法用法和上面一样,只是从字符串的末尾开始搜索。
以上是Python中字符串搜索的方法,可以选择满足自己需求的方法来解决问题~希望能解决你的问题。
