相关疑难解决方法(0)

在Python中查找所有出现的子字符串

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 regex string

325
推荐指数
12
解决办法
39万
查看次数

在Python中查找字符串中多次出现的字符串

如何在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 string

64
推荐指数
5
解决办法
15万
查看次数

具有重叠事件的字符串计数

计算给定字符串出现次数的最佳方法是什么,包括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中有更好的方法吗?

python string search

50
推荐指数
4
解决办法
5万
查看次数

标签 统计

python ×3

string ×3

regex ×1

search ×1