String exact match

后端 未结 7 1688
悲哀的现实
悲哀的现实 2020-11-29 08:13

I have a string in which the word \"LOCAL\" occurs many times. I used the find() function to search for this word but it returns another word \"Locally\" as wel

7条回答
  •  鱼传尺愫
    2020-11-29 09:13

    For this kind of thing, regexps are very useful :

    import re
    
    print(re.findall('\\blocal\\b', "Hello, locally local test local."))
    // ['local', 'local']
    

    \b means word boundary, basically. Can be space, punctuation, etc.

    Edit for comment :

    print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE))
    // Hello, ***** locally ***** test *****.
    

    You can remove flags=re.IGNORECASE if you don't want to ignore the case, obviously.

提交回复
热议问题