I\'m trying to locate all index positions of a string in a list of words and I want the values returned as a list. I would like to find the string if it is on its own, or if
You don't need to assign the result of match
back to x
. And your match should be on x
rather than list
.
Also, you need to use re.search
instead of re.match
, since your the regex pattern '\W*myString\W*'
will not match the first element. That's because test;
is not matched by \W*
. Actually, you only need to test for immediate following and preceding character, and not the complete string.
So, you can rather use word boundaries
around the string:
pattern = r'\b' + re.escape(myString) + r'\b'
indices = [i for i, x in enumerate(myList) if re.search(pattern, x)]