0

I have a list as below:

a_list=['i']

I also have this string:

a_string='i dont know where i belong but i know i am okay here'

How would I iterate over the string to find each index where the list term occurs? I was thinking of doing linear search but I am already within a function and can't figure out how to import the list from the outer function to the nested function where I would define the linear search.

Edit: I found the answer to this after some time. I was simply unsure of how functions could work in other functions. I was worried that nesting functions within each other could lead to errors.

Veneratu
  • 17
  • 6
  • *"import the list from the outer function"*? What do you mean exactly? Please [edit] and add your code. Otherwise, this is a duplicate of [Find all the occurrences of a character in a string](/q/13009675/4518341) or [How to find all occurrences of a substring?](/q/4664850/4518341) BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Aug 24 '21 at 19:29

2 Answers2

3

The simplest approach will be to to iterate the string using enumerate, and take the index whenever value matches:

>>> [i for i,v in enumerate(a_string) if v==a_list[0]]
[0, 18, 31, 38]

I'm taking the first value in above iteration using a_list[0] but you can easily add another loop for multiple values in a_list

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
2

If you are looking for the index of the WORD in the sentence then you can split the sentence into a list:

>>> a_string='i dont know where i belong but i know i am okay here'
>>> [i for i, x in enumerate(a_string.split(' ')) if x == "i"]
[0, 4, 7, 9]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
JNevill
  • 46,980
  • 4
  • 38
  • 63