Python中对字符串查找有几种方法,用法是什么
Admin 2022-06-06 群英技术资讯 740 次浏览
在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中常用于时间的模块有time、datetime 和 calendar,顾名思义 time 是表示时间(时、分、秒、毫秒)等,calendar 是表示日历时间的,本章先讨论 datetime 模块,需要的朋友可以参考下
由于项目取数需要,要将两个不同的csv文件合并到一个文件中,所以下面这篇文章主要给大家介绍了关于利用python合并csv文件的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
要求给定指定的行、列以及对应的工作表作为参数,能够正确解析合并单元格,获取指定单元格的值。如果直接根据行列获取对应单元格的值,则合并单元格非左上角的其他单元格都会获取到None值。
这篇文章主要为大家介绍了Python并行编程多线程锁机制Lock与RLock实现线程同步示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
这篇文章主要介绍了python 如何破解加密zip文件的密码,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008