点击查看【bilibili】

    查找:
    所谓字符串查找⽅法即是查找⼦串在字符串中的位置或出现的次数。

    • find():检测某个⼦串是否包含在这个字符串中,如果在返回这个⼦串开始的位置下标,否则则返回-1。

    语法:

    1. 字符串序列.find(⼦串, 开始位置下标, 结束位置下标)

    注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。

    学习代码如下:

    1. mystr = "hello world and itcast and itheima and Python"
    2. # 1、find()
    3. # print(mystr.find('and')) # 12
    4. # print(mystr.find('and',15,30)) # 23
    5. # print(mystr.find('ands')) # -1 ands子串不存在
    • index():检测某个⼦串是否包含在这个字符串中,如果在返回这个⼦串开始的位置下标,否则则报异常。

    语法:

    1. 字符串序列.index(⼦串, 开始位置下标, 结束位置下标)

    注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。

    学习代码如下:

    1. mystr = "hello world and itcast and itheima and Python"
    2. # index()
    3. # print(mystr.index('and')) # 12
    4. # print(mystr.index('and',15,30)) #23
    5. print(mystr.index ('ands')) # 如果index查找子串不存在,报错
    • rfifind(): 和fifind()功能相同,但查找⽅向为右侧开始。

    学习代码如下:

    1. mystr = "hello world and itcast and itheima and Python"
    2. # rfind()
    3. # print(mystr.rfind('and')) # 35
    4. # print(mystr.rfind('ands')) # -1
    • rindex():和index()功能相同,但查找⽅向为右侧开始。

    学习代码如下:

    1. mystr = "hello world and itcast and itheima and Python"
    2. # rindex
    3. # print(mystr.rindex('and')) # 35
    4. # print(mystr.rindex('ands')) # 报错
    • count():返回某个⼦串在字符串中出现的次数

    语法:

    1. 字符串序列.count(⼦串, 开始位置下标, 结束位置下标)

    开始和结束位置下标可以省略,表示在整个字符串序列中查找。

    学习代码如下:

    1. mystr = "hello world and itcast and itheima and Python"
    2. # count()
    3. # print(mystr.count('and',15,30)) # 1
    4. # print(mystr.count('and')) # 3
    5. # print(mystr.count('ands')) # 0