Find substring in string but only if whole words?

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

    Excuse me REGEX fellows, but the simpler answer is:

    text = "this is the esquisidiest piece never ever writen"
    word = "is"
    " {0} ".format(text).lower().count(" {0} ".format(word).lower())
    

    The trick here is to add 2 spaces surrounding the 'text' and the 'word' to be searched, so you guarantee there will be returning only counts for the whole word and you don't get troubles with endings and beginnings of the 'text' searched.

提交回复
热议问题