0

I tried to map the index where spaces are provided in a given string. But the problem was I couldn't find the index of multiple spaces. Only the first space index was shown.

This is my sample explanation:

Y="Hell o World!"
print(Y.index(" "))
Output: 4

I'm not able to map the space on index: 6

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • 2
    ```index``` only returns the first instance of the substring. You can do ```[i for i,j in enumerate(Y) if j==' ']``` –  Aug 24 '21 at 06:47
  • [Here](https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string) they discussed the issue. Maybe one of those solutions is fitting for you – Finn Aug 24 '21 at 06:49
  • Does this answer your question? [Find the nth occurrence of substring in a string](https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string) – Finn Aug 24 '21 at 06:49
  • https://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python – CarlosSR Aug 24 '21 at 06:49
  • Does this answer your question? [Finding multiple occurrences of a string within a string in Python](https://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python) – SuperStormer Aug 24 '21 at 18:50

3 Answers3

3

You can do the following:
According to documentation

str.index is like find(), but raise ValueError when the substring is not found.

And for find()

Return the lowest index in the string where substring sub is found within the slice s[start:end]

In your string, 4 is the first or the lowest index where python found a space: ' '

>>> Y="Hell o World!"
>>> [i for i,j in enumerate(Y) if j==' ']
[4, 6]
1
import re
Y = "Hell o World"
occurences_list = [m.start() for m in re.finditer(' ', Y)]

print(occurences_list) # [4, 6]
Daniel
  • 1,895
  • 9
  • 20
1

Using a custom function and yield :

def findall(text, pattern):
    '''Yields all the positions of the pattern in the text.'''
    i = text.find(pattern)
    while i != -1:
        yield i
        i = text.find(pattern, i+1)

Y = "Hell o World"
print(list(findall(Y, ' ')) # [4, 6]
heretolearn
  • 6,387
  • 4
  • 30
  • 53