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

后端 未结 7 2056
再見小時候
再見小時候 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:44

    Break up the string into a list of strings with .split() then use the in operator.

    This is much simpler than using regular expressions.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 18:48

    Below is a solution without using regular expressions. The program searches for exact word in this case 'CASINO' and prints the sentence.

        words_list = [ "The Learn Python Challenge Casino.", "They bought a car while at 
        the casino", "Casinoville" ]
        search_string = 'CASINO'
        def text_manipulation(words_list, search_string):
            search_result = []
            for sentence in words_list:
                words = sentence.replace('.', '').replace(',', '').split(' ')
                [search_result.append(sentence) for w in words if w.upper() == 
                  search_string]
            print(search_result)
    
        text_manipulation(words_list, search_string)
    

    This will print the results - ['The Learn Python Challenge Casino.', 'They bought a car while at the casino']

    0 讨论(0)
  • 2020-12-01 18:56

    I suspect that you are looking for the startswith() function. This checks to see if the characters in a string match at the start of another string

    "abcde".startswith("abc") -> true
    
    "abcde".startswith("bcd") -> false
    

    There is also the endswith() function, for checking at the other end.

    0 讨论(0)
  • 2020-12-01 19:00

    Actually, you should look for 'This is correct' string surrounded by word boundaries.

    So

    import re
    
    if re.search(r'\bThis is correct\b', text):
        print('correct')
    

    should work for you.

    0 讨论(0)
  • 2020-12-01 19:01

    You can make a few changes.

    elif 'This is correct' in text[:len('This is correct')]:
    

    or

    elif ' This is correct ' in ' '+text+' ':
    

    Both work. The latter is more flexible.

    0 讨论(0)
提交回复
热议问题