There are several problems with your code. First, you need to map expr to the list item ( x ), not the entire list ( myList ). Secondly, to insert a variable into an expression, you must use + (string concatenation). And finally, use raw literals ( r'\W ) to correctly interpret the slash in expr:
import re myList = ['test;cow', 'one', 'two', 'three', 'cow.', 'cow', 'acow'] myString = 'cow' indices = [i for i, x in enumerate(myList) if re.match(r'\W*' + myString + r'\W*', x)] print indices
If it is likely that myString contains special regular expression characters (for example, a slash or a period), you also need to apply re.escape to it:
regex = r'\W*' + re.escape(myString) + r'\W*' indices = [i for i, x in enumerate(myList) if re.match(regex, x)]
As pointed out in the comments, perhaps the best option:
regex = r'\b' + re.escape(myString) + r'\b' indices = [i for i, x in enumerate(myList) if re.search(regex, x)]
georg
source share