Python目录字符串中某重复字符的位置
Python索引字符串中某重复字符的位置
譬如字符串为s,字符e在s中出现了两次,用find()或index()都只能找到第一个e的位置,请问如何才能同时找到第二个e的位置?
------解决方案--------------------
譬如字符串为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 - 1 8 >>>
------解决方案--------------------
可以把找到位置的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 ... 5 8
------解决方案--------------------
- 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 #输出 5 8