Check if string appears as its own word - Python

前端 未结 4 453
生来不讨喜
生来不讨喜 2021-01-23 15:55

Let\'s say that I am looking for the word \"or\". What I want is to check whether that word appears as a word or as a substring of another word.

E.g.

<
4条回答
  •  隐瞒了意图╮
    2021-01-23 16:36

    You can use a regular expression for this:

    import re
    
    def contains_word(text, word):
        return bool(re.search(r'\b' + re.escape(word) + r'\b', text))
    
    print(contains_word('or', 'or')) # True
    print(contains_word('for', 'or')) # False
    print(contains_word('to be or not to be', 'or')) # True
    

提交回复
热议问题