String exact match

Below you can use simple function.

def find_word(text, search):

   result = re.findall('\\b'+search+'\\b', text, flags=re.IGNORECASE)
   if len(result)>0:
      return True
   else:
      return False

Using:

text = "Hello, LOCAL locally local test local."
search = "local"
if find_word(text, search):
  print "i Got it..."
else:
  print ":("

line1 = "This guy is local"
line2 = "He lives locally"

if "local" in line1.split():
    print "Local in line1"
if "local" in line2.split():
    print "Local in line2"

Only line1 will match.


For this kind of thing, regexps are very useful :

import re

print(re.findall('\\blocal\\b', "Hello, locally local test local."))
// ['local', 'local']

\b means word boundary, basically. Can be space, punctuation, etc.

Edit for comment :

print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE))
// Hello, ***** locally ***** test *****.

You can remove flags=re.IGNORECASE if you don't want to ignore the case, obviously.

Tags:

Python

String