![图片[1]-Python中字符串如何查找?-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/1607674439981080.png)
在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!GoCheckit!')
注意:
find()和index()只能找到第一个索引值。如果指定字符同时存在多个,只会输出第一个指定字符的索引值。
rfind和rindex方法用法和上面一样,只是从字符串的末尾开始查找。
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容