Find substring in string but only if whole words?

前端 未结 7 693
囚心锁ツ
囚心锁ツ 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:35

    Here's a way to do it without a regex (as requested) assuming that you want any whitespace to serve as a word separator.

    import string
    
    def find_substring(needle, haystack):
        index = haystack.find(needle)
        if index == -1:
            return False
        if index != 0 and haystack[index-1] not in string.whitespace:
            return False
        L = index + len(needle)
        if L < len(haystack) and haystack[L] not in string.whitespace:
            return False
        return True
    

    And here's some demo code (codepad is a great idea: Thanks to Felix Kling for reminding me)

    0 讨论(0)
提交回复
热议问题