Check If string Is In bigger String

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?


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'bw+b',s,re.U)) if j==w]
... 
>>> finder(test_str,word)
[0, 3, 6, 7]
链接地址: http://www.djcxy.com/p/55074.html

上一篇: 使用python 2.7.5将pdf文件打印成“Adobe pdf”打印机

下一篇: 检查字符串是否大于字符串