Python中字符串如何查找?

来源:千锋教育
发布时间:2023-11-08 03:52:22
分享

在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方法用法和上面一样,只是从字符串的末尾开始查找。

以上内容为大家介绍了Python中字符串如何查找?希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

声明:本站部分稿件版权来源于网络,如有侵犯版权,请及时联系我们。

相关推荐

  • python 类的总结 1.什么是绑定到对象的方法,如何定义,如何调用,给谁用?有什么特性?2.什么是绑定到类的方法,如何定义,如何调用,给谁用?有什么特性?3.什么是解除绑定的函数,如何定义,如何调用,给谁用?有什么特性?
  • python 二次加工标准类型(包装) 包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们刚学的继承/派生知识(其他的标准类型均
  • python 的不可变对象 在python中一切皆对象。在Python中不存在所谓的值传递调用,一切传递都是对象的引用,也可认为是传址。python中,对象分为可变(mutable)和不可变(immutable)两种类型,元组(
  • python 面向对象(OOP)的三大特征 (1)面向对象程序设计有三大特征:封装(Encapsulation)、继承(Inheritance)、多态(Polymorphism)。这三个单词很常见,大家还是记住为好!(2)封装(Encapsul
  • python 中的多态 python中的鸭子类型允许我们使用任何提供所需方法的对象,而不需要迫使它成为一个子类。由于python属于动态语言,当你定义了一个基类和基类中的方法,并编写几个继承该基类的子类时,由于python在
  • python 列表排序 使用列表对象的sort()方法进行原地排序,支持多种不同的排序方法。>>>aList=[3,4,5,6,7,9,11,13,15,17]>>>importrandom>>>random.shuffle