Find substring in string but only if whole words?

前端 未结 7 770
囚心锁ツ
囚心锁ツ 2020-11-27 07:32

What is an elegant way to look for a string within another string in Python, but only if the substring is within whole words, not part of a word?

Perhaps an example

7条回答
  •  半阙折子戏
    2020-11-27 08:17

    You can use regular expressions and the word boundary special character \b (highlight by me):

    Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that \b is defined as the boundary between \w and \W, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

    def string_found(string1, string2):
       if re.search(r"\b" + re.escape(string1) + r"\b", string2):
          return True
       return False
    

    Demo


    If word boundaries are only whitespaces for you, you could also get away with pre- and appending whitespaces to your strings:

    def string_found(string1, string2):
       string1 = " " + string1.strip() + " "
       string2 = " " + string2.strip() + " "
       return string2.find(string1)
    

提交回复
热议问题