title: python regex selecting whole words
body: <p>I am writing a script that introduces misspellings into sentence. I am using python re module to replace the original word with the misspelling. The script looks like this: </p>
  
  <pre><code># replacing original word by error
  pattern = re.compile(r'%s' % original_word)    
  replace_by = r'\1' + err
  modified_sentence = re.sub(pattern, replace_by, sentence, count=1)
  </code></pre>
  
  <p>But the problem is this will replace even if original_word was part of another word for example: </p>
  
  <p>If i had </p>
  
  <pre><code>original_word = 'in'
  err = 'il'
  sentence = 'eating food in'
  </code></pre>
  
  <p>it would replace the occurrence of 'in' in eating like:</p>
  
  <pre><code>&gt; 'eatilg food in'
  </code></pre>
  
  <p>I was checking in the <a href="https://docs.python.org/2/howto/regex.html" rel="nofollow">re documentation</a> but it doesn't give any example on how to include regex options, for example: </p>
  
  <p>If my pattern is:</p>
  
  <pre><code>regex_pattern = '\b%s\b' % original_word
  </code></pre>
  
  <p>this would solve the problem as \b represents 'word boundary'. But it doesn't seem to work. </p>
  
  <p>I tried to find to find a work around it by doing: </p>
  
  <pre><code>pattern = re.compile(r'([^\w])%s' % original_word)
  </code></pre>
  
  <p>but that does not work. For example : </p>
  
  <pre><code>original_word = 'to'
  err = 'vo'
  sentence = 'I will go tomorrow to the'
  </code></pre>
  
  <p>it replaces it to:</p>
  
  <pre><code>&gt; I will go vomorrow to the 
  </code></pre>
  
  <p>Thank you, any help appreciated</p>