发布网友 发布时间:2022-04-24 17:52
共5个回答
懂视网 时间:2022-04-18 18:26
下面为大家分享一篇Python 查找字符在字符串中的位置实例,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧str_1='wo shi yi zhi da da niu ' char_1='i' nPos=str_1.index(char_1) print(nPos)
运行结果:7
========是使用find==========
str_1='wo shi yi zhi da da niu ' char_1='i' nPos=str_1.find(char_1) print(nPos)
结果:5
========如何查找所有‘i'在字符串中位置呢?===========
#开挂模式 str_1='wo shi yi zhi da da niu ' char_1=str(input('Please input the Char you want:')) count=0 str_list=list(str_1) for each_char in str_list: count+=1 if each_char==char_1: print(each_char,count-1)
运行结果:
Please input the Char you want:i i 0 i 1 i 2 i 3
热心网友 时间:2022-04-18 15:34
Python编程中对字符串进行搜索查找,并返回字符位置,案例代码如下:
# multiple searches of a string for a substring热心网友 时间:2022-04-18 16:52
用re吧
热心网友 时间:2022-04-18 18:27
>>> def find_pos(str, tobefind):
... L = len(tobefind)
... def xiter():
... for i, c in enumerate(str):
... if c==tobefind[0] and str[i:i+L] == tobefind:
... yield i
... return list(xiter())
...
>>> find_pos('test test tst testa testb', 'test')
[0, 5, 14, 20]
>>>
热心网友 时间:2022-04-18 20:18
#常规循环版
def findn(cs,ms,n=1):
finalLoc=0
matchLen=len(ms)
for i in range(n):
midLoc=cs.index(ms)
cs=cs[(midLoc+matchLen):]
if i==0:
finalLoc+=midLoc
else:
finalLoc+=midLoc+matchLen
return finalLoc
#递归版
def findn(cs,ms,n=1,loc=0):
if n==1:
return loc+cs.index(ms)
else:
start=cs.index(ms)+len(ms)
return findn(cs[start:],ms,n-1,start+loc)
print findn('abaabbbbbab','a',3)
#生成器版
def findn(cs,ms,loc=0):
nloc=cs.find(ms)
if nloc!=-1:
start=nloc+len(ms)
yield nloc+loc
for i in findn(cs[start:],ms,start+loc):
yield i
print list(findn('aaaababbbabab','ab'))