读书人

Python索引字符串中某重复字符的位置,

发布时间: 2013-01-25 15:55:29 作者: rapoo

Python索引字符串中某重复字符的位置
譬如字符串为s,字符e在s中出现了两次,用find()或index()都只能找到第一个e的位置,请问如何才能同时找到第二个e的位置?

>>> s = 'you me he'
>>> s.find('e')
5
>>> s.index('e')
5

[解决办法]
>>> import re
>>> s = 'you me he'
>>> rs = re.search(r'e[^e]+(e)', s)
>>> print rs.endpos - 1
8
>>>


>>> s.find('e', s.index('e') + 1)
8
>>>

[解决办法]
可以把找到位置的e替换掉:
>>> s = 'you me he'
>>> s = list(s)
>>> while(1):
... if 'e' in s:
... index = s.index('e')
... print index
... s[index] = '*'
... else:
... break
...
5
8

[解决办法]

>>> s = 'you me he'
>>> index=-1
>>> while True:
index = s.find('e',index+1)#从index+1位置开始找,如果找到返回索引,没找到则返回-1
if index==-1:#没找到 跳出
break
print index

#输出
5
8

读书人网 >perl python

热点推荐