Find substring in string but only if whole words?

前端 未结 7 734
囚心锁ツ
囚心锁ツ 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条回答
  •  -上瘾入骨i
    2020-11-27 08:34

    One approach using the re, or regex, module that should accomplish this task is:

    import re
    
    string1 = "pizza pony"
    string2 = "who knows what a pizza pony is?"
    
    search_result = re.search(r'\b' + string1 + '\W', string2)
    
    print(search_result.group())
    

提交回复
热议问题