Python中对字符串查找有几种方法,用法是什么
Admin 2022-06-06 群英技术资讯 630 次浏览
在Python使用字符串的过程中,如果遇到很多的字符串,想要查找到想要的字符串有些困难。本文主要介绍Python字符串查找的几种方法:find方法、 index方法、rfind方法、rindex方法。具体请看如下内容:
find方法
find方法获取值时,如果要查找的值不存在,会返回-1
str.find(str, beg=0, end=len(string))
使用实例
# string in which we have to find the sub_string str = "Hello world, how are you?" # sub_string to find the given string sub_str = "how" # find by sub_str print (str.find (sub_str)) # find by sub_str with slice:start index print (str.find (sub_str, 10)) # find by sub_str with slice:start index and slice: end index print (str.find (sub_str, 10, 24)) # find a sub_str that does not exist sub_str = "friend" # find by sub_str print (str.find (sub_str)) # find a sub_str with different case sub_str = "HOW" # find by sub_str print (str.find (sub_str))
输出
13 13 13 -1 -1
index方法
在获取值得索引时,如果不存在值,会报错
str.index(str, beg=0, end=len(string))
使用实例
def second_index(text: str, symbol: str): """ returns the second index of symbol in a given text """ try: return text.index(symbol, text.index(symbol) + 1) except ValueError: return None if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing print('Example:') print(second_index("sims", "s")) assert second_index("sims", "s") == 3, "First" assert second_index("find the river", "e") == 12, "Second" assert second_index("hi", " ") is None, "Third" assert second_index("hi mayor", " ") is None, "Fourth" assert second_index("hi mr Mayor", " ") == 5, "Fifth" print('You are awesome! All tests are done! Go Check it!')
注意:
find()和index()只能找到第一个索引值。如果指定字符同时存在多个,只会输出第一个指定字符的索引值。
rfind和rindex方法用法和上面一样,只是从字符串的末尾开始查找。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
python标准库思维导图:1、操作系统接口os模块提供了不少与操作系统相关联的函数。>>> import os>>> os.getcwd() # 返回当前的工作目录'C:\\Python34'>>> os.ch
这篇文章主要为大家介绍了Django自动发现所有路由的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助<BR>
这篇文章主要为大家介绍了pytest官方文档解读fixtures调用fixtures及fixture复用性,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
这篇文章主要介绍了Python爬虫进阶之Beautiful Soup库详解,文中有非常详细的代码示例,对正在学习python爬虫的小伙伴们有非常好的帮助,需要的朋友可以参考下
这篇文章我们来了解怎样用python怎样实现扑克游戏中判断牌型的功能,在扑克游戏,判断牌型是很基础的操作,这才能进行游戏的下一步。下面我们就来看看具体要怎样去实现。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008