-1

Python3 I am looking for a way to check if any element inside my list, is contained within target string. Now - if the condition is met, I need to get the index.

I have learned about the .find() method but it only compares one value and I need a way to test them all and get the position.

Edit: Many thanks for the answers! That's the stuff

2 Answers2

0

If there's only one target string to search ("haystack"), and it's not absurdly huge (billions of characters), or the number of strings to be searched for ("needles") is smallish, just do the linear scans the naive way:

 haystack = '....'
 needles = ['...', '...']
 hits = {}
 for needle in needles:
     try:
         hits[needle] = haystack.index(needle)
     except ValueError:
         pass  # needle not found

 # Or if exceptions aren't allowed, test and check
 for needle in needles:
     idx = haystack.find(needle)
     if idx >= 0:
         hits[needle] = idx

If you've got many needles to search for in many (or huge) haystacks, you can get major speed-ups from Aho-Corasick string search, which I've already covered in detail here.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Your question is vague. However, here is what I'm guessing you're asking for.

targ_string = 'hello world'
elements = ['a', 'b' 'c', 'd']

for char in elements:
    # will print the index of the character in the string, and -1 if it wasn't found
    print('The index of',char,'is',targ_string.find(char))
Output:
--------------------------
The index of a is -1
The index of bc is -1
The index of d is 10
ObjectJosh
  • 601
  • 3
  • 14