4

I'm working with Python v2.7, and I'm trying to find out if you can tell if a word is in a string.

If for example i have a string and the word i want to find:

str = "ask and asked, ask are different ask. ask"
word = "ask"

How should i code so that i know that the result i obtain doesn't include words that are part of other words. In the example above i want all the "ask" except the one "asked".

I have tried with the following code but it doesn't work:

def exact_Match(str1, word):
    match = re.findall(r"\\b" + word + "\\b",str1, re.I)
    if len(match) > 0:
        return True
    return False 

Can someone please explain how can i do it?

2
  • 1
    use single backslash in raw strings. Commented Apr 28, 2015 at 11:36
  • What Casimir is basically saying is either use r"\b" or use "\\b". In your snippet, the correct call would thus be either r"\b" + word + r"\b" or "\\b" + word + "\\b" Commented Apr 28, 2015 at 11:54

1 Answer 1

3

You can use the following function :

>>> test_str = "ask and asked, ask are different ask. ask"
>>> word = "ask"

>>> def finder(s,w):
...   return re.findall(r'\b{}\b'.format(w),s,re.U)
... 
>>> finder(text_str,word)
['ask', 'ask', 'ask', 'ask']

Note that you need \b for boundary regex!

Or you can use the following function to return the indices of words : in splitted string :

>>> def finder(s,w):
...   return [i for i,j in enumerate(re.findall(r'\b\w+\b',s,re.U)) if j==w]
... 
>>> finder(test_str,word)
[0, 3, 6, 7]
Sign up to request clarification or add additional context in comments.

4 Comments

DON'T use str for variable names because this overrides the str() function.
I have a problem, the word is in utf-8 and this gives me an error.
@FranciscoF What kind of error? you can also use re.U flag in findall function!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.