How do I check for an EXACT word in a string in python

后端 未结 7 2058
再見小時候
再見小時候 2020-12-01 18:27

Basically I need to find a way to figure out a way to find the EXACT word in a string. All the information i have read online has only given me how to search for letters in

7条回答
  •  醉梦人生
    2020-12-01 18:45

    You can use the word-boundaries of regular expressions. Example:

    import re
    
    s = '98787This is correct'
    for words in ['This is correct', 'This', 'is', 'correct']:
        if re.search(r'\b' + words + r'\b', s):
            print('{0} found'.format(words))
    

    That yields:

    is found
    correct found
    

    EDIT: For an exact match, replace \b assertions with ^ and $ to restrict the match to the begin and end of line.

提交回复
热议问题