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) 我有一个子字符串:
substring = "please help me out"
Run Code Online (Sandbox Code Playgroud)
我有另一个字符串:
string = "please help me out so that I could solve this"
Run Code Online (Sandbox Code Playgroud)
如何查找是否substring是string使用Python 的子集?
我试图在Python 2.6中使用re在一系列更大的数字中找到每10个数字系列的数字.
我很容易就能抓住没有重叠的比赛,但我想要数字系列中的每场比赛.例如.
在"123456789123456789"
我应该得到以下列表:
[1234567891,2345678912,3456789123,4567891234,5678912345,6789123456,7891234567,8912345678,9123456789]
Run Code Online (Sandbox Code Playgroud)
我发现了对"前瞻"的引用,但我看过的例子只显示了数字对而不是更大的分组,我无法将它们转换为超出两位数.
如何在Python中的字符串中找到多次出现的字符串?考虑一下:
>>> text = "Allowed Hello Hollow"
>>> text.find("ll")
1
>>>
Run Code Online (Sandbox Code Playgroud)
所以第一次出现的ll是1,如预期的那样.我如何找到它的下一个出现?
同样的问题对列表有效.考虑:
>>> x = ['ll', 'ok', 'll']
Run Code Online (Sandbox Code Playgroud)
如何查找所有ll索引?
计算给定字符串出现次数的最佳方法是什么,包括python中的重叠?这是最明显的方式:
def function(string, str_to_search_for):
count = 0
for x in xrange(len(string) - len(str_to_search_for) + 1):
if string[x:x+len(str_to_search_for)] == str_to_search_for:
count += 1
return count
function('1011101111','11')
returns 5
Run Code Online (Sandbox Code Playgroud)
?
或者在python中有更好的方法吗?
我对一个非常简单的字符串计数操作感到困惑:
s = 'BANANA'
s.count('ANA')
Run Code Online (Sandbox Code Playgroud)
这应该会得到 2,对吗?由于子字符串 ,ANA在 中出现了 2 次BANANA。
但结果我得到了 1。
>>> s = 'BANANA'
>>> s.count('ANA')
1
Run Code Online (Sandbox Code Playgroud)
不知道为什么结果错误。就是这么简单的操作!
感谢任何帮助。
PS:我该如何解决这个问题?