读书人

Python目录字符串中某重复字符的位置

发布时间: 2012-09-13 09:51:52 作者: rapoo

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

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


[解决办法]
Python code
>>> import re>>> s = 'you me he'>>> rs = re.search(r'e[^e]+(e)', s)>>> print rs.endpos - 18>>>
[解决办法]
可以把找到位置的e替换掉:
Assembly code
>>> s = 'you me he'>>> s = list(s)>>> while(1):...     if 'e' in s:...             index = s.index('e')...             print index...             s[index] = '*'...     else:...             break...58
[解决办法]
Python code
>>> s = 'you me he'>>> index=-1>>> while True:        index = s.find('e',index+1)#从index+1位置开始找,如果找到返回索引,没找到则返回-1        if index==-1:#没找到 跳出            break        print index#输出    58 

读书人网 >perl python

热点推荐