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]

要统计出现次数,请参见计算字符串中子字符串出现的次数。


当前回答

src = input() # we will find substring in this string
sub = input() # substring

res = []
pos = src.find(sub)
while pos != -1:
    res.append(pos)
    pos = src.find(sub, pos + 1)

其他回答

其他人提供的解决方案完全基于可用的find()方法或任何可用的方法。

找出a的所有出现点的核心基本算法是什么 字符串中的子字符串?

def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

你也可以继承str类到新的类,并可以使用这个函数 在下面。

class newstr(str):
def find_all(string,substring):
    """
    Function: Returning all the index of substring in a string
    Arguments: String and the search string
    Return:Returning a list
    """
    length = len(substring)
    c=0
    indexes = []
    while c < len(string):
        if string[c:c+length] == substring:
            indexes.append(c)
        c=c+1
    return indexes

调用方法

newstr。find_all('你觉得这个答案有用吗?然后upvote 这个!”、“这”)

查找给定字符串中某个字符的所有出现次数,并作为字典返回 例如:你好 结果: {'h':1, 'e':1, 'l':2, 'o':1}

def count(string):
   result = {}
   if(string):
     for i in string:
       result[i] = string.count(i)
     return result
   return {}

否则你就像这样

from collections import Counter

   def count(string):
      return Counter(string)

我遇到了同样的问题,我是这样做的:

hw = 'Hello oh World!'
list_hw = list(hw)
o_in_hw = []

while True:
    o = hw.find('o')
    if o != -1:
        o_in_hw.append(o)
        list_hw[o] = ' '
        hw = ''.join(list_hw)
    else:
        print(o_in_hw)
        break

我在编码方面很新,所以你可以简化它(如果计划连续使用,当然要让它成为一个函数)。

所有和所有的工作都是为了我所做的。

编辑:请考虑这是单一字符,它会改变你的变量,所以你必须在一个新变量中创建一个字符串的副本来保存它,我没有把它放在代码中,因为它很容易,它只是为了展示我是如何使它工作的。

你可以试试:

>>> string = "test test test test"
>>> for index,value in enumerate(string):
    if string[index:index+(len("test"))] == "test":
        print index

0
5
10
15

来,让我们一起递归。

def locations_of_substring(string, substring):
    """Return a list of locations of a substring."""

    substring_length = len(substring)    
    def recurse(locations_found, start):
        location = string.find(substring, start)
        if location != -1:
            return recurse(locations_found + [location], location+substring_length)
        else:
            return locations_found

    return recurse([], 0)

print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]

不需要这样使用正则表达式。