title: How do you use a regex in a list comprehension in Python?
body: <p>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 it is preceded or followed by punctuation, but not if it is a substring of a larger word.</p>
  
  <p>The following code only captures "cow" only and misses both "test;cow" and "cow." </p>
  
  <pre><code>myList = ['test;cow', 'one', 'two', 'three', 'cow.', 'cow', 'acow']
  myString = 'cow'
  indices = [i for i, x in enumerate(myList) if x == myString]
  print indices
  &gt;&gt; 5
  </code></pre>
  
  <p>I have tried changing the code to use a regular expression:</p>
  
  <pre><code>import re
  myList = ['test;cow', 'one', 'two', 'three', 'cow.', 'cow', 'acow']
  myString = 'cow'
  indices = [i for i, x in enumerate(myList) if x == re.match('\W*myString\W*', myList)]
  print indices
  </code></pre>
  
  <p>But this gives an error: expected string or buffer</p>
  
  <p>If anyone knows what I'm doing wrong I'd be very happy to hear. I have a feeling it's something to do with the fact I'm trying to use a regular expression in there when it's expecting a string. Is there a solution?</p>
  
  <p>The output I'm looking for should read:</p>
  
  <pre><code>&gt;&gt; [0, 4, 5]
  </code></pre>
  
  <p>Thanks</p>