• 技术文章 >Python技术 >Python基础教程

    python:在字符串中查找指定字符的多个索引方法

    宋雪维宋雪维2020-12-03 17:41:18原创9404

    Python中查找字符串指定字符的常用方法有find()、index()。
    用法:

    1

    2

    3

    4

    5

    str = 'abcd'

     

    print(str.find('c')) #输出即为查找指定字符的索引值

     

    print(str.index('c')) #输出即为查找指定字符的索引值

    区别:
    当指定字符在该字符串中不存在时,find输出为-1.index则会报错,如下:

    1

    2

    3

    4

    5

    str = 'abcd'

     

    print(str.find('f'))  #-1

     

    print(str.index('f')) #ValueError: substring not found

    缺点:
    find()和index()只能找到第一个索引值。如果指定字符同时存在多个,只会输出第一个指定字符的索引值。
    需要说明的是:Python并没有内置方法可直接解决这个问题。所以需要自己定义一个方法去解决这个问题。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    lstKey = [] #定义空列表用于存储多个指定字符的索引

    lengthKey = 0

    str = input('字符串:')

    key = input('要查找的关键字:')

    #字符串中存在指定字符串的个数

    countStr = str.count(key)

    #利用获取的countStr进行判断

    if countStr < 1:

        print('该字符串中无要查找的字符')

    elif countStr == 1: #当字符串中只有一个指定字符时,直接通过find()方法即可解决

        indexKey = str.find(key)

        print('查找的关键字的索引为:',indexKey)

    else: #当字符串中存在多个指定字符的处理方法

        #第一个指定字符的处理方法

        indexKey = str.find(key)

        lstKey.append(indexKey) #将第一个索引加入到lstKey列表中

        #其余指定字符的处理方法

        while countStr > 1:

            #将前一个指定字符之后的字符串截取下来

            str_new = str[indexKey+1:len(str)+1]

            #获取截取后的字符串中前一个指定字符的索引值

            indexKey_new = str_new.find(key)

            #后一个索引值=前一个索引值+1+indexkey_new

            indexKey = indexKey+1 +indexKey_new

            #将后发现的索引值加入lstKey列表中

            lstKey.append(indexKey)

            countStr -= 1

        print('查找的关键字的索引为',lstKey)



    专题推荐:python字符串
    上一篇:python compile函数怎么用? 下一篇:python-字符串替换

    相关文章推荐

    • python中repr函数是怎么用的?• python subprocess.popen怎么用?• python实战:画正弦函数图像

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网