
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)
|