Using regular expressions, you can use re.finditer to find all (non-overlapping) occurences:

>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
         print('ll found', m.start(), m.end())

ll found 1 3
ll found 10 12
ll found 16 18

Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use str.find to get the next index:

>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
        index = text.find('ll', index)
        if index == -1:
            break
        print('ll found at', index)
        index += 2 # +2 because len('ll') == 2

ll found at  1
ll found at  10
ll found at  16

This also works for lists and other sequences.

Answer from poke on Stack Overflow
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-ndash-multiple-indices-replace-in-string
Python โ€“ Multiple Indices Replace in String
September 1, 2023 - Hello Python!" indices = [0, 6, 13] # Get characters at specified indices and create pattern chars_to_replace = [text[index] for index in indices] pattern = '|'.join([re.escape(char) for char in chars_to_replace]) # Replace using regex new_text = re.sub(pattern, '#', text) print("Modified string:", new_text) Modified string: #ello #orld! #ello Pyt#on! Use list conversion for efficient multiple index replacements.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_index.asp
Python String index() Method
Remove List Duplicates Reverse a String Add Two Numbers ยท Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The index() method finds the first occurrence of the specified value.
Discussions

Help with .index()? finding multiple instances of item
The easy way would be to just use enumerate on the list, and then manually iterate the list and find the indices yourself. More on reddit.com
๐ŸŒ r/learnpython
9
3
March 11, 2023
How do I replace a string at multiple indices (Python)? - Stack Overflow
I have a string and I want to replace characters at certain indices of that string. But I only know how to replace a character if I got one index using: ... pos in this case is the index. But when I now have a list of multiple indices (so pos is a list now), it does not work, because slice ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How do I get the index of multiple occurrences of the same character in a string? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
Get multiple strings from array indices - PYTHON - Stack Overflow
Is there a feature in python that allows this without iterating over the whole array within a for word in myArray ... What I get is an index in a loop which only tells me up to which word I should "print" it. More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 24, 2018
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ help with .index()? finding multiple instances of item
r/learnpython on Reddit: Help with .index()? finding multiple instances of item
March 11, 2023 -

Taken from https://www.programiz.com/python-programming/online-compiler/?ref=409055e9 :

vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of the first 'i' is returned

index = vowels.index('i')

print('The index of i:', index)

Output: The index of i: 2

Say that the list was much bigger, and you don't know the contents, but you know 'i' is in it more than once. What would be the best way to find all instances of 'i'?

Thanks so much! <3

Top answer
1 of 5
5
The easy way would be to just use enumerate on the list, and then manually iterate the list and find the indices yourself.
2 of 5
3
str.index() has parameters start and end, which can be used to define the starting index for the search. So, if you know that you have more than one substring in your string, you can do the following: test = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry' i_idx = test.index('i') // i_idx -> 12 i_idx = test.index('i', i_idx+1) // i_idx -> 16 You can use it in the loop, but note that the str.index() throws an exception if the substring is not found. So, you can loop until you stop finding the substring in your string like this: test = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry' i_idx = 0 while True: try: i_idx = test.index('i', i_idx+1) print(i_idx) except ValueError as e: print(e) break Output: 12 16 42 45 61 65 substring not found There is a sibling function, str.find(). It works the same, but it does not raise exception, instead it returns -1 when the substring is not found, so you can loop until the result of str.find() is -1 to find indices of all substring occurrences in your string: test = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry' i_idx = 0 while (i_idx := test.find('i', i_idx+1)) > 0: print(i_idx) Output: 12 16 42 45 61 65 There is a function str.count() which can be used in a loop as well: i_idx = 0 for _ in range(test.count('i')): i_idx = test.index('i', i_idx+1) print(i_idx) The disadvantages of all the above method is that you have a time complexity of O(m*n) for a string with length n and m occurences of your substring in your string, with or O(n**2) for the worst case. Better time complexity can be achieved if you simply iterate through the string only once: for idx, char in enumerate(test): if char == 'i': print(idx) or using comprehensions generator expression (as pointed out by u/kyber/ : indices = (idx for idx, char in enumerate(test) if char == 'i') print(*indices)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-multiple-indices-replace-in-string
Multiple Indices Replace in String - Python - GeeksforGeeks
July 12, 2025 - s = "geeksforgeeks is best" li = [2, 4, 7, 10] # Indices to replace ch = '*' # Replacement character temp = list(s) res = [ch if idx in li else ele for idx, ele in enumerate(temp)] res = ''.join(res) print("The String after performing replace:", res) ... Using list comprehension we check each character's index (idx) in temp, if the index is in li then it replaces the character with ch.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-multiple-indices-replace-in-string
Multiple Indices Replace in String โ€“ Python | GeeksforGeeks
January 17, 2025 - For loop iterates through the indices provided in li and for each index the string is updated by replacing the character at that specific index. ... In Python, replacing multiple lines in a file consists of updating specific contents within a text file. This can be done using various modules ...
Find elsewhere
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ how-to-index-and-slice-strings-in-python-3
How To Index and Slice Strings in Python | DigitalOcean
Learn how to index and slice strings in Python 3 with step-by-step examples. Master substring extraction, negative indexing, and slice notation.
Top answer
1 of 3
1

Create a new str to avoid change the main_str:

main_str = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
indexes_list = [
    {
      "type": "first_type",
      "startOffset": 0,
      "endOffset": 5,
    },
    {
      "type": "second_type",
      "startOffset": 16,
      "endOffset": 22,
    }
]

new_str = ""
index = 0
for i in indexes_list:
    start = i["startOffset"]
    end = i["endOffset"]
    new_str += main_str[index: start] + "<span>" + main_str[start:end] + "</span>"
    index = end
new_str += main_str[index:]
print(new_str)
2 of 3
1

Here is a solution without any imperative for loops. It still uses plenty of looping for the list comprehensions.

# Get all the indices and label them as starts or ends.
starts = [(o['startOffset'], True) for o in indexes_list]
ends = [(o['endOffset'], False) for o in indexes_list]

# Sort everything...
all_indices = sorted(starts + ends)

# ...so it is possible zip together adjacent pairs and extract substrings.
pieces = [
    (s[1], main_str[s[0]:e[0]])
    for s, e in zip(all_indices, all_indices[1:])
]

# And then join all the pieces together with a bit of conditional formatting.
formatted = ''.join([
    f"<span>{part}</span>" if is_start else part
    for is_start, part in pieces
])

formatted
# '<span>Lorem</span> Ipsum is s<span>imply </span>dummy text of the printing and typesetting industry.'

Also, although you said you do not want for loops, it is important to note that you do not have to do any index modification if you do the updates in reverse order.

def update_str(s, spans): 
    for lookup in sorted(spans, reverse=True, key=lambda o: o['startOffset']): 
        start = lookup['startOffset'] 
        end = lookup['endOffset'] 
        before, span, after = s[:start], s[start:end], s[end:] 
        s = f'{before}<span>{span}</span>{after}' 
    return s 

update_str(main_str, indexes_list)                                                                                                                                                                                                   
# '<span>Lorem</span> Ipsum is s<span>imply </span>dummy text of the printing and typesetting industry.'
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68046416 โ€บ how-to-i-return-the-index-of-multiple-characters-in-a-string-when-running-a-for
python - how to I return the index of multiple characters in a string when running a for loop? - Stack Overflow
dup = ["aaa","bbb","ccc"] s = "hfidgfaaahjfihdfhd" for duplicate in dup: if duplicate in s: for index in range(s.index(duplicate), s.index(duplicate) + len(duplicate)): print(index) You can avoid the *list(range()) using a regular for loop with the range function ... Save this answer. ... Show activity on this post. ... dup = ['aaa', 'bbb', 'ccc'] s = "hhdahwhdaaadfewfeas" for i in range(0, len(s), len(dup[0]) - 1): string_to_check = s[i:3+i:] if dup[0] == string_to_check: for j in range(0, len(string_to_check)): print(f'Index for the letters: {j + i}')
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-all-occurrences-of-substring-in-string
Python - All occurrences of substring in string - GeeksforGeeks
January 10, 2025 - Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task.ร‚ Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.findit
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ string_index.htm
Python String index() Method
If there is more than one space in the input string, then the first space encountered in the input string is considered as the resultant index. str1 = "Hello! Welcome to Tutorialspoint." str2 = " "; result= str1.index(str2) print("The index ...
๐ŸŒ
Hashnode
codingwithestefania.hashnode.dev โ€บ python-string-indexing-how-to-get-characters
Python String Indexing - How to Get Individual Characters
February 22, 2024 - This technique is called String Slicing. ๐Ÿž ... Here, we are using the integer 2 directly for the examples, but you can also use a variable as the index to assign and update the value dynamically.