import re def find_substring_indexes(str1, str2): matches = re.compile(f'(?=({str1}))', re.IGNORECASE).finditer(str2) return [match.span()[0] for match in matches] def sub_string_matches(str1, str2, str3): matchIndexes = find_substring_indexes(str1, str2) offset = 0 newString = str2 for i in range(len(matchIndexes)): realIndex = matchIndexes[i] + offset try: if len(str3) - len(str1) - (matchIndexes[i+1] - matchIndexes[i]) > 0: reverseOffset = len(str3) - len(str1) - (matchIndexes[i+1] - matchIndexes[i]) else: reverseOffset = 0 except IndexError: reverseOffset = 0 pass newString = newString[:realIndex] + str3 + newString[realIndex + len(str1) - reverseOffset:] offset += len(str3) - len(str1) + reverseOffset return newString if __name__ == "__main__": print(find_substring_indexes('iS', "Is this the real life? Is this just fantasy?")) print(find_substring_indexes(str1 = "oo", str2 = "Never let you go let me go. Never let me go ooo")) print(sub_string_matches(str1 = "iS", str2 = "Is this the real life? Is this just fantasy?", str3 = "cool")) print(sub_string_matches(str1 = "oo", str2 = "Never let you goooo let me goo. Never let me goo oooo", str3 = "cool"))