Python已经string.find()并且string.rfind()在字符串中获取子字符串的索引.
我想知道,也许有类似的东西string.find_all()可以返回所有已创建的索引(不仅从开始或从头到尾)?
例如:
string = "test test test test"
print string.find('test') # 0
print string.rfind('test') # 15
#this is the goal
print string.find_all('test') # [0,5,10,15]
Run Code Online (Sandbox Code Playgroud) 如何计算Python中字符串中给定子字符串的出现次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
Run Code Online (Sandbox Code Playgroud) 我需要从HTML源文件中找到表单的内容,我做了一些搜索并找到了很好的方法来做到这一点,但问题是它只打印出第一个找到的,我怎么能循环它并输出所有的表单内容,而不是只是第一个?
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matchObj = re.search('<form>(.*?)</form>', line, re.S)
print matchObj.group(1)
# Output: Form 1
# I need it to output every form content he found, not just first one...
Run Code Online (Sandbox Code Playgroud) 给定一个模式[1,1,0,1,1]和一个长度为 100 的二进制列表,[0,1,1,0,0,...,0,1]. 我想计算此列表中此模式的出现次数。有没有一种简单的方法可以做到这一点,而无需使用变量跟踪每个索引处的每个项目?
请注意,[...,1, 1, 0, 1, 1, 1, 1, 0, 1, 1,...,0]可能会发生这样的事情,但这应该计为 2 次。