Find substring in string but only if whole words?

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

    The simplest and most pythonic way, I believe, is to break the strings down into individual words and scan for a match:

    
        string = "My Name Is Josh"
        substring = "Name"
    
        for word in string.split():
            if substring == word:
                print("Match Found")
    
    

    For a bonus, here's a oneliner:

    any([substring == word for word in string.split()])
    

提交回复
热议问题